Java Code Examples for android.media.MediaExtractor#setDataSource()

The following examples show how to use android.media.MediaExtractor#setDataSource() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MediaUtils.java    From MusicPlus with Apache License 2.0 6 votes vote down vote up
/**
 * 该音频是否符合采样率是sampleRate,通道数是channelCount,值为-1表示忽略该条件
 * 
 * @param audioFile
 * @param sampleRate
 * @param channelCount
 * @return
 */
public static boolean isMatchAudioFormat(String audioFile, int sampleRate,int channelCount){
	MediaExtractor mex = new MediaExtractor();
    try {
        mex.setDataSource(audioFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    MediaFormat mf = mex.getTrackFormat(0);
    
    boolean result = true;
    if(sampleRate != -1){
    	result = sampleRate == mf.getInteger(MediaFormat.KEY_SAMPLE_RATE);
    }
    
    if(result && channelCount != -1){
    	result = channelCount == mf.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
    }

    mex.release();
    
    return result;
}
 
Example 2
Source File: Track.java    From K-Sonic with MIT License 6 votes vote down vote up
public void initStream() throws Exception {
    mLock.lock();
    try {
        mExtractor = new MediaExtractor();
        if (!TextUtils.isEmpty(mPath)) {
            mExtractor.setDataSource(mPath);
        } else if (mUri != null) {
            mExtractor.setDataSource(mContext, mUri, null);
        } else {
            throw new IOException();
        }
    } catch (Exception e) {//IOException
        throw e;
    } finally {
        mLock.unlock();
    }
    initConfig();
}
 
Example 3
Source File: VideoDecoder.java    From rtmp-rtsp-stream-client-java with Apache License 2.0 6 votes vote down vote up
public boolean initExtractor(String filePath) throws IOException {
  decoding = false;
  videoExtractor = new MediaExtractor();
  videoExtractor.setDataSource(filePath);
  for (int i = 0; i < videoExtractor.getTrackCount() && !mime.startsWith("video/"); i++) {
    videoFormat = videoExtractor.getTrackFormat(i);
    mime = videoFormat.getString(MediaFormat.KEY_MIME);
    if (mime.startsWith("video/")) {
      videoExtractor.selectTrack(i);
    } else {
      videoFormat = null;
    }
  }
  if (videoFormat != null) {
    width = videoFormat.getInteger(MediaFormat.KEY_WIDTH);
    height = videoFormat.getInteger(MediaFormat.KEY_HEIGHT);
    duration = videoFormat.getLong(MediaFormat.KEY_DURATION);
    return true;
    //video decoder not supported
  } else {
    mime = "";
    videoFormat = null;
    return false;
  }
}
 
Example 4
Source File: MediaMoviePlayer.java    From AudioVideoPlayerSample with Apache License 2.0 6 votes vote down vote up
/**
 * @param sourceFile
 * @return first video track index, -1 if not found
 */
protected int internalPrepareVideo(final String sourceFile) {
	int trackIndex = -1;
	mVideoMediaExtractor = new MediaExtractor();
	try {
		mVideoMediaExtractor.setDataSource(sourceFile);
		trackIndex = selectTrack(mVideoMediaExtractor, "video/");
		if (trackIndex >= 0) {
			mVideoMediaExtractor.selectTrack(trackIndex);
	        final MediaFormat format = mVideoMediaExtractor.getTrackFormat(trackIndex);
        	mVideoWidth = format.getInteger(MediaFormat.KEY_WIDTH);
        	mVideoHeight = format.getInteger(MediaFormat.KEY_HEIGHT);
        	mDuration = format.getLong(MediaFormat.KEY_DURATION);

			if (DEBUG) Log.v(TAG, String.format("format:size(%d,%d),duration=%d,bps=%d,framerate=%f,rotation=%d",
				mVideoWidth, mVideoHeight, mDuration, mBitrate, mFrameRate, mRotation));
		}
	} catch (final IOException e) {
		Log.w(TAG, e);
	}
	return trackIndex;
}
 
Example 5
Source File: Video.java    From Camera-Roll-Android-App with Apache License 2.0 6 votes vote down vote up
public int retrieveFrameRate() {
    MediaExtractor extractor = new MediaExtractor();
    int frameRate = -1;
    try {
        //Adjust data source as per the requirement if file, URI, etc.
        extractor.setDataSource(getPath());
        int numTracks = extractor.getTrackCount();
        for (int i = 0; i < numTracks; i++) {
            MediaFormat format = extractor.getTrackFormat(i);
            if (format.containsKey(MediaFormat.KEY_FRAME_RATE)) {
                frameRate = format.getInteger(MediaFormat.KEY_FRAME_RATE);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //Release stuff
        extractor.release();
    }
    return frameRate;
}
 
Example 6
Source File: VideoPlayer.java    From media-for-mobile with Apache License 2.0 6 votes vote down vote up
public void open(String path) throws IOException {
    close();

    pause = false;
    stop = false;
    seekRequestedToMs = -1;
    currentPresentationTimeMs = 0;

    extractor = new MediaExtractor();

    extractor.setDataSource(path);

    if (initWithTrackOfInterest("video/") == false) {
        throw new IOException("Can't open video file. Unsupported video format.");
    }

    if (codec == null) {
        throw new IOException("Can't open video file. Unsupported video format.");
    }

    pause();

    videoThread = new VideoThread();
    videoThread.start();
}
 
Example 7
Source File: VideoBgmAddAction.java    From SimpleVideoEditor with Apache License 2.0 5 votes vote down vote up
private String getBgmMime() throws IOException {
    String mine = null;

    MediaExtractor extractor = new MediaExtractor();
    extractor.setDataSource(mBgmFile.getAbsolutePath());
    for (int i = 0; i < extractor.getTrackCount(); i++) {
        MediaFormat mediaFormat = extractor.getTrackFormat(i);
        if (mediaFormat.getString(MediaFormat.KEY_MIME).startsWith("audio")) {
            mine = mediaFormat.getString(MediaFormat.KEY_MIME);
            break;
        }
    }

    return mine;
}
 
Example 8
Source File: MediaMoviePlayer.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * @param source
 * @return first video track index, -1 if not found
 */
@SuppressLint("NewApi")
protected int internal_prepare_video(final Object source) throws IOException {
	int trackindex = -1;
	mVideoMediaExtractor = new MediaExtractor();
	if (source instanceof String) {
		mVideoMediaExtractor.setDataSource((String)source);
	} else if (source instanceof AssetFileDescriptor) {
		if (BuildCheck.isAndroid7()) {
			mVideoMediaExtractor.setDataSource((AssetFileDescriptor)source);
		} else {
			mVideoMediaExtractor.setDataSource(((AssetFileDescriptor)source).getFileDescriptor());
		}
	} else {
		// ここには来ないけど
		throw new IllegalArgumentException("unknown source type:source=" + source);
	}
	trackindex = selectTrack(mVideoMediaExtractor, "video/");
	if (trackindex >= 0) {
		mVideoMediaExtractor.selectTrack(trackindex);
		final MediaFormat format = mVideoMediaExtractor.getTrackFormat(trackindex);
		mVideoWidth = format.getInteger(MediaFormat.KEY_WIDTH);
		mVideoHeight = format.getInteger(MediaFormat.KEY_HEIGHT);
		mDuration = format.getLong(MediaFormat.KEY_DURATION);

		if (DEBUG) Log.v(TAG, String.format("format:size(%d,%d),duration=%d,bps=%d,framerate=%f,rotation=%d",
			mVideoWidth, mVideoHeight, mDuration, mBitrate, mFrameRate, mRotation));
	}
	return trackindex;
}
 
Example 9
Source File: VideoProcessor.java    From VideoProcessor with Apache License 2.0 5 votes vote down vote up
public void setDataSource(MediaExtractor extractor) throws IOException {
    if(inputPath!=null){
        extractor.setDataSource(inputPath);
    }else{
        extractor.setDataSource(context,inputUri,null);
    }
}
 
Example 10
Source File: VideoUtil.java    From VideoProcessor with Apache License 2.0 5 votes vote down vote up
public static Pair<Integer, Integer> getVideoFrameCount(String input) throws IOException {
    MediaExtractor extractor = new MediaExtractor();
    extractor.setDataSource(input);
    int trackIndex = VideoUtil.selectTrack(extractor, false);
    extractor.selectTrack(trackIndex);
    int keyFrameCount = 0;
    int frameCount = 0;
    while (true) {
        int flags = extractor.getSampleFlags();
        if (flags > 0 && (flags & MediaExtractor.SAMPLE_FLAG_SYNC) != 0) {
            keyFrameCount++;
        }
        long sampleTime = extractor.getSampleTime();
        if (sampleTime < 0) {
            break;
        }
        frameCount++;
        extractor.advance();
    }
    extractor.release();
    return new Pair<>(keyFrameCount, frameCount);
}
 
Example 11
Source File: VideoCutAction.java    From SimpleVideoEditor with Apache License 2.0 5 votes vote down vote up
private void prepare() throws IOException {
    mMediaExtractor = new MediaExtractor();
    mMediaExtractor.setDataSource(mInputFile.getAbsolutePath());
    //  out put format is mp4
    mMediaMuxer = new MediaMuxer(mOutputFile.getAbsolutePath(),
            MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
    mMediaMuxer.setOrientationHint(VideoUtil.getVideoRotation(mInputFile));
}
 
Example 12
Source File: AudioTransCoder.java    From SimpleVideoEditor with Apache License 2.0 5 votes vote down vote up
private void prepare() throws IOException {
    extractor = new MediaExtractor();
    extractor.setDataSource(mInputFile.getAbsolutePath());
    int numTracks = extractor.getTrackCount();
    for (int i = 0; i < numTracks; i++) {
        MediaFormat format = extractor.getTrackFormat(i);
        String mine = format.getString(MediaFormat.KEY_MIME);
        if (!TextUtils.isEmpty(mine) && mine.startsWith("audio")) {
            extractor.selectTrack(i);
            if (mDurationMs == 0) {
                try {
                    mDurationMs = format.getLong(MediaFormat.KEY_DURATION) / 1000;
                } catch (Exception e) {
                    e.printStackTrace();
                    MediaPlayer mediaPlayer = new MediaPlayer();
                    mediaPlayer.setDataSource(mInputFile.getAbsolutePath());
                    mediaPlayer.prepare();
                    mDurationMs = mediaPlayer.getDuration();
                    mediaPlayer.release();
                }
            }

            if (mDurationMs == 0) {
                throw new IllegalStateException("We can not get duration info from input file: " + mInputFile);
            }

            decoder = MediaCodec.createDecoderByType(mine);
            decoder.configure(format, null, null, 0);
            decoder.start();
            break;
        }
    }
}
 
Example 13
Source File: VideoResampler.java    From AndroidVideoSamples with Apache License 2.0 5 votes vote down vote up
private MediaExtractor setupExtractorForClip(SamplerClip clip ) {

      
      MediaExtractor extractor = new MediaExtractor();
      try {
         extractor.setDataSource( clip.getUri().toString() );
      } catch ( IOException e ) {
         e.printStackTrace();
         return null;
      }

      return extractor;
   }
 
Example 14
Source File: MediaInput.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public @NonNull MediaExtractor createExtractor() throws IOException {
  final MediaExtractor extractor = new MediaExtractor();
  extractor.setDataSource(file.getAbsolutePath());
  return extractor;
}
 
Example 15
Source File: VideoBgmRemoveAction.java    From SimpleVideoEditor with Apache License 2.0 4 votes vote down vote up
private void prepare() throws IOException {
    mMediaExtractor = new MediaExtractor();
    mMediaExtractor.setDataSource(mInputFile.getAbsolutePath());
    mMediaMuxer = new MediaMuxer(mOutputFile.getAbsolutePath(), MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
    mMediaMuxer.setOrientationHint(VideoUtil.getVideoRotation(mInputFile));
}
 
Example 16
Source File: MediaMoviePlayer.java    From libcommon with Apache License 2.0 4 votes vote down vote up
/**
 * @param source
 * @return first audio track index, -1 if not found
 */
@SuppressLint("NewApi")
protected int internal_prepare_audio(final Object source) throws IOException {
	int trackindex = -1;
	mAudioMediaExtractor = new MediaExtractor();
	if (source instanceof String) {
		mAudioMediaExtractor.setDataSource((String)source);
	} else if (source instanceof AssetFileDescriptor) {
		if (BuildCheck.isAndroid7()) {
			mVideoMediaExtractor.setDataSource((AssetFileDescriptor)source);
		} else {
			mVideoMediaExtractor.setDataSource(((AssetFileDescriptor)source).getFileDescriptor());
		}
	} else {
		// ここには来ないけど
		throw new IllegalArgumentException("unknown source type:source=" + source);
	}
	trackindex = selectTrack(mAudioMediaExtractor, "audio/");
	if (trackindex >= 0) {
		mAudioMediaExtractor.selectTrack(trackindex);
		final MediaFormat format = mAudioMediaExtractor.getTrackFormat(trackindex);
		mAudioChannels = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
		mAudioSampleRate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE);
		final int min_buf_size = AudioTrack.getMinBufferSize(mAudioSampleRate,
			(mAudioChannels == 1 ? AudioFormat.CHANNEL_OUT_MONO : AudioFormat.CHANNEL_OUT_STEREO),
			AudioFormat.ENCODING_PCM_16BIT);
		final int max_input_size = format.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE);
		mAudioInputBufSize =  min_buf_size > 0 ? min_buf_size * 4 : max_input_size;
		if (mAudioInputBufSize > max_input_size) mAudioInputBufSize = max_input_size;
		final int frameSizeInBytes = mAudioChannels * 2;
		mAudioInputBufSize = (mAudioInputBufSize / frameSizeInBytes) * frameSizeInBytes;
		if (DEBUG) Log.v(TAG, String.format("getMinBufferSize=%d,max_input_size=%d,mAudioInputBufSize=%d",min_buf_size, max_input_size, mAudioInputBufSize));
		//
		mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
			mAudioSampleRate,
			(mAudioChannels == 1 ? AudioFormat.CHANNEL_OUT_MONO : AudioFormat.CHANNEL_OUT_STEREO),
			AudioFormat.ENCODING_PCM_16BIT,
			mAudioInputBufSize,
			AudioTrack.MODE_STREAM);
		try {
			mAudioTrack.play();
		} catch (final Exception e) {
			Log.e(TAG, "failed to start audio track playing", e);
			mAudioTrack.release();
			mAudioTrack = null;
		}
	}
	return trackindex;
}
 
Example 17
Source File: BaseTransformationFragment.java    From LiTr with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@NonNull
protected void updateSourceMedia(@NonNull SourceMedia sourceMedia, @NonNull Uri uri) {
    sourceMedia.uri = uri;
    sourceMedia.size = TranscoderUtils.getSize(getContext(), uri);

    try {
        MediaExtractor mediaExtractor = new MediaExtractor();
        mediaExtractor.setDataSource(getContext(), uri, null);
        sourceMedia.tracks = new ArrayList<>(mediaExtractor.getTrackCount());

        for (int track = 0; track < mediaExtractor.getTrackCount(); track++) {
            MediaFormat mediaFormat = mediaExtractor.getTrackFormat(track);
            String mimeType = mediaFormat.getString(MediaFormat.KEY_MIME);
            if (mimeType == null) {
                continue;
            }

            if (mimeType.startsWith("video")) {
                VideoTrackFormat videoTrack = new VideoTrackFormat(track, mimeType);
                videoTrack.width = getInt(mediaFormat, MediaFormat.KEY_WIDTH);
                videoTrack.height = getInt(mediaFormat, MediaFormat.KEY_HEIGHT);
                videoTrack.duration = getLong(mediaFormat, MediaFormat.KEY_DURATION);
                videoTrack.frameRate = getInt(mediaFormat, MediaFormat.KEY_FRAME_RATE);
                videoTrack.keyFrameInterval = getInt(mediaFormat, MediaFormat.KEY_I_FRAME_INTERVAL);
                videoTrack.rotation = getInt(mediaFormat, KEY_ROTATION, 0);
                videoTrack.bitrate = getInt(mediaFormat, MediaFormat.KEY_BIT_RATE);
                sourceMedia.tracks.add(videoTrack);
            } else if (mimeType.startsWith("audio")) {
                AudioTrackFormat audioTrack = new AudioTrackFormat(track, mimeType);
                audioTrack.channelCount = getInt(mediaFormat, MediaFormat.KEY_CHANNEL_COUNT);
                audioTrack.samplingRate = getInt(mediaFormat, MediaFormat.KEY_SAMPLE_RATE);
                audioTrack.duration = getLong(mediaFormat, MediaFormat.KEY_DURATION);
                audioTrack.bitrate = getInt(mediaFormat, MediaFormat.KEY_BIT_RATE);
                sourceMedia.tracks.add(audioTrack);
            } else {
                sourceMedia.tracks.add(new GenericTrackFormat(track, mimeType));
            }
        }
    } catch (IOException ex) {
        Log.e(TAG, "Failed to extract sourceMedia", ex);
    }

    sourceMedia.notifyChange();
}
 
Example 18
Source File: MediaInput.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public @NonNull MediaExtractor createExtractor() throws IOException {
  final MediaExtractor extractor = new MediaExtractor();
  extractor.setDataSource(mediaDataSource);
  return extractor;
}
 
Example 19
Source File: ExternalMediaRecordActivity.java    From PLDroidShortVideo with Apache License 2.0 4 votes vote down vote up
private boolean getSourceVideoParameters() {
    mSrcMediaExtractor = new MediaExtractor();
    try {
        mSrcMediaExtractor.setDataSource(SRC_VIDEO_FILE_PATH);
    } catch (IOException e) {
        Log.e(TAG, "file video setDataSource failed: " + e.getMessage());
        return false;
    }

    final int srcVideoTrackIndex = findTrack(mSrcMediaExtractor, "video/");
    if (srcVideoTrackIndex < 0) {
        Log.e(TAG, "cannot find video in file!");
        return false;
    }
    final int srcAudioTrackIndex = findTrack(mSrcMediaExtractor, "audio/");
    if (srcAudioTrackIndex < 0) {
        Log.e(TAG, "cannot find audio in file!");
        return false;
    }

    mSrcVideoFormat = mSrcMediaExtractor.getTrackFormat(srcVideoTrackIndex);
    if (mSrcVideoFormat == null) {
        Log.e(TAG, "cannot find video format!");
        return false;
    }
    if (mSrcVideoFormat.containsKey(MediaFormat.KEY_WIDTH)) {
        mVideoFrameWidth = mSrcVideoFormat.getInteger(MediaFormat.KEY_WIDTH);
    }
    if (mSrcVideoFormat.containsKey(MediaFormat.KEY_HEIGHT)) {
        mVideoFrameHeight = mSrcVideoFormat.getInteger(MediaFormat.KEY_HEIGHT);
    }
    if (mSrcVideoFormat.containsKey(MediaFormat.KEY_FRAME_RATE)) {
        mFrameRate = mSrcVideoFormat.getInteger(MediaFormat.KEY_FRAME_RATE);
    }

    mSrcAudioFormat = mSrcMediaExtractor.getTrackFormat(srcAudioTrackIndex);
    if (mSrcAudioFormat == null) {
        Log.e(TAG, "cannot find audio format!");
        return false;
    }
    if (mSrcAudioFormat.containsKey(MediaFormat.KEY_SAMPLE_RATE)) {
        mSampleRate = mSrcAudioFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE);
    }
    if (mSrcAudioFormat.containsKey(MediaFormat.KEY_CHANNEL_COUNT)) {
        mChannels = mSrcAudioFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
    }
    Log.i(TAG, "Video width:" + mVideoFrameWidth + ", height:" + mVideoFrameHeight + ", framerate:" + mFrameRate + "; Audio samplerate: " + mSampleRate + ", channels:" + mChannels);

    return true;
}
 
Example 20
Source File: MediaInput.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public @NonNull MediaExtractor createExtractor() throws IOException {
  final MediaExtractor extractor = new MediaExtractor();
  extractor.setDataSource(context, uri, null);
  return extractor;
}