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

The following examples show how to use android.media.MediaExtractor#getTrackFormat() . 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: MediaMoviePlayer.java    From AudioVideoPlayerSample with Apache License 2.0 6 votes vote down vote up
/**
 * @param media_extractor
 * @param trackIndex
 * @return
 */
protected MediaCodec internalStartAudio(final MediaExtractor media_extractor, final int trackIndex) {
	if (DEBUG) Log.v(TAG, "internalStartAudio:");
	MediaCodec codec = null;
	if (trackIndex >= 0) {
        final MediaFormat format = media_extractor.getTrackFormat(trackIndex);
        final String mime = format.getString(MediaFormat.KEY_MIME);
		try {
			codec = MediaCodec.createDecoderByType(mime);
			codec.configure(format, null, null, 0);
	        codec.start();
	    	if (DEBUG) Log.v(TAG, "internalStartAudio:codec started");
	    	//
	        final ByteBuffer[] buffers = codec.getOutputBuffers();
	        int sz = buffers[0].capacity();
	        if (sz <= 0)
	        	sz = mAudioInputBufSize;
	        if (DEBUG) Log.v(TAG, "AudioOutputBufSize:" + sz);
	        mAudioOutTempBuf = new byte[sz];
		} catch (final IOException e) {
			Log.w(TAG, e);
			codec = null;
		}
	}
	return codec;
}
 
Example 2
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 3
Source File: ExtractMpegFramesTest.java    From Android-MediaCodec-Examples with Apache License 2.0 6 votes vote down vote up
/**
 * Selects the video track, if any.
 *
 * @return the track index, or -1 if no video track is found.
 */
private int selectTrack(MediaExtractor extractor) {
    // Select the first video track we find, ignore the rest.
    int numTracks = extractor.getTrackCount();
    for (int i = 0; i < numTracks; i++) {
        MediaFormat format = extractor.getTrackFormat(i);
        String mime = format.getString(MediaFormat.KEY_MIME);
        if (mime.startsWith("video/")) {
            if (VERBOSE) {
                Log.d(TAG, "Extractor selected track " + i + " (" + mime + "): " + format);
            }
            return i;
        }
    }

    return -1;
}
 
Example 4
Source File: MoviePlayer.java    From grafika with Apache License 2.0 6 votes vote down vote up
/**
 * Selects the video track, if any.
 *
 * @return the track index, or -1 if no video track is found.
 */
private static int selectTrack(MediaExtractor extractor) {
    // Select the first video track we find, ignore the rest.
    int numTracks = extractor.getTrackCount();
    for (int i = 0; i < numTracks; i++) {
        MediaFormat format = extractor.getTrackFormat(i);
        String mime = format.getString(MediaFormat.KEY_MIME);
        if (mime.startsWith("video/")) {
            if (VERBOSE) {
                Log.d(TAG, "Extractor selected track " + i + " (" + mime + "): " + format);
            }
            return i;
        }
    }

    return -1;
}
 
Example 5
Source File: AudioRecordThread.java    From PhotoMovie with Apache License 2.0 6 votes vote down vote up
private int selectTrack(MediaExtractor extractor, boolean audio) {
    int numTracks = extractor.getTrackCount();
    for (int i = 0; i < numTracks; i++) {
        MediaFormat format = extractor.getTrackFormat(i);
        String mime = format.getString(MediaFormat.KEY_MIME);
        if (audio) {
            if (mime.startsWith("audio/")) {
                return i;
            }
        } else {
            if (mime.startsWith("video/")) {
                return i;
            }
        }
    }
    return -5;
}
 
Example 6
Source File: MediaMoviePlayer.java    From AudioVideoPlayerSample with Apache License 2.0 6 votes vote down vote up
/**
 * @param media_extractor
 * @param trackIndex
 * @return
 */
protected MediaCodec internalStartVideo(final MediaExtractor media_extractor, final int trackIndex) {
	if (DEBUG) Log.v(TAG, "internalStartVideo:");
	MediaCodec codec = null;
	if (trackIndex >= 0) {
        final MediaFormat format = media_extractor.getTrackFormat(trackIndex);
        final String mime = format.getString(MediaFormat.KEY_MIME);
		try {
			codec = MediaCodec.createDecoderByType(mime);
			codec.configure(format, mOutputSurface, null, 0);
	        codec.start();
		} catch (final IOException e) {
			Log.w(TAG, e);
			codec = null;
		}
    	if (DEBUG) Log.v(TAG, "internalStartVideo:codec started");
	}
	return codec;
}
 
Example 7
Source File: MediaController.java    From react-native-video-helper with MIT License 6 votes vote down vote up
@TargetApi(16)
private int selectTrack(MediaExtractor extractor, boolean audio) {
    int numTracks = extractor.getTrackCount();
    for (int i = 0; i < numTracks; i++) {
        MediaFormat format = extractor.getTrackFormat(i);
        String mime = format.getString(MediaFormat.KEY_MIME);
        if (audio) {
            if (mime.startsWith("audio/")) {
                return i;
            }
        } else {
            if (mime.startsWith("video/")) {
                return i;
            }
        }
    }
    return -5;
}
 
Example 8
Source File: VideoRecoder.java    From deltachat-android with GNU General Public License v3.0 6 votes vote down vote up
@TargetApi(16)
private int selectTrack(MediaExtractor extractor, boolean audio) {
  int numTracks = extractor.getTrackCount();
  for (int i = 0; i < numTracks; i++) {
    MediaFormat format = extractor.getTrackFormat(i);
    String mime = format.getString(MediaFormat.KEY_MIME);
    if (audio) {
      if (mime.startsWith("audio/")) {
        return i;
      }
    } else {
      if (mime.startsWith("video/")) {
        return i;
      }
    }
  }
  return -5;
}
 
Example 9
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 10
Source File: VideoResampler.java    From AndroidVideoSamples with Apache License 2.0 5 votes vote down vote up
private int getVideoTrackIndex(MediaExtractor extractor) {

      for ( int trackIndex = 0; trackIndex < extractor.getTrackCount(); trackIndex++ ) {
         MediaFormat format = extractor.getTrackFormat( trackIndex );

         String mime = format.getString( MediaFormat.KEY_MIME );
         if ( mime != null ) {
            if ( mime.equals( "video/avc" ) ) {
               return trackIndex;
            }
         }
      }

      return -1;
   }
 
Example 11
Source File: VideoUtil.java    From VideoProcessor with Apache License 2.0 5 votes vote down vote up
public static int selectTrack(MediaExtractor extractor, boolean audio) {
    int numTracks = extractor.getTrackCount();
    for (int i = 0; i < numTracks; i++) {
        MediaFormat format = extractor.getTrackFormat(i);
        String mime = format.getString(MediaFormat.KEY_MIME);
        if (audio) {
            if (mime.startsWith("audio/")) {
                return i;
            }
        } else {
            if (mime.startsWith("video/")) {
                return i;
            }
        }
    }
    return -5;
}
 
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: BaseAudioDecoder.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void initMediaComponents() throws Exception {
    if(targetSampleRate <= 0){
        throw new InstantiationException("Target sample rate of " + targetSampleRate + " is unsupported");
    }

    extractor = new MediaExtractor();
    Context contextRef = contextWeakReference.get();
    if(contextRef == null){
        throw new InstantiationException("Context reference was null");
    }
    extractor.setDataSource(contextRef, audioSource, null);
    MediaFormat format = null;
    String mime = null;

    // Select the first audio track we find.
    int numTracks = extractor.getTrackCount();
    for (int i = 0; i < numTracks; ++i) {
        MediaFormat f = extractor.getTrackFormat(i);
        String m = f.getString(MediaFormat.KEY_MIME);
        if (m.startsWith("audio/")) {
            format = f;
            mime = m;
            extractor.selectTrack(i);
            break;
        }
    }

    if (mime == null) {
        throw new Exception("The audio file " + audioSource.getPath() + " doesn't contain an audio track.");
    }

    decoder = MediaCodec.createDecoderByType(mime);
    decoder.configure(format, null, null, 0);
}
 
Example 14
Source File: MediaUtil.java    From EZFilter with MIT License 5 votes vote down vote up
/**
 * 读取多媒体第一个视频轨和音频轨
 *
 * @param extractor
 * @return
 */
public static Track getFirstTrack(MediaExtractor extractor) {
    Track track = new Track();
    track.videoTrackIndex = -1;
    track.audioTrackIndex = -1;
    int trackCount = extractor.getTrackCount();
    for (int i = 0; i < trackCount; i++) {
        MediaFormat format = extractor.getTrackFormat(i);
        String mime = format.getString(MediaFormat.KEY_MIME);
        if (track.videoTrackIndex < 0 && mime.startsWith("video/")) {
            track.videoTrackIndex = i;
            track.videoTrackMime = mime;
            track.videoTrackFormat = format;
        } else if (track.audioTrackIndex < 0 && mime.startsWith("audio/")) {
            track.audioTrackIndex = i;
            track.audioTrackMime = mime;
            track.audioTrackFormat = format;
        }
        if (track.videoTrackIndex >= 0 && track.audioTrackIndex >= 0) break;
    }

    if (track.videoTrackIndex < 0 && track.audioTrackIndex < 0) {
        // 视频轨和音轨都没有
        Log.e("MediaUtil", "Not found video/audio track.");
        return null;
    } else {
        return track;
    }
}
 
Example 15
Source File: VideoThumbnailsExtractor.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
static void extractThumbnails(final @NonNull MediaInput input,
                              final int thumbnailCount,
                              final int thumbnailResolution,
                              final @NonNull Callback callback)
{
  MediaExtractor extractor     = null;
  MediaCodec     decoder       = null;
  OutputSurface  outputSurface = null;
  try {
    extractor = input.createExtractor();
    MediaFormat mediaFormat = null;
    for (int index = 0; index < extractor.getTrackCount(); ++index) {
      if (extractor.getTrackFormat(index).getString(MediaFormat.KEY_MIME).startsWith("video/")) {
        extractor.selectTrack(index);
        mediaFormat = extractor.getTrackFormat(index);
        break;
      }
    }
    if (mediaFormat != null) {
      final String mime     = mediaFormat.getString(MediaFormat.KEY_MIME);
      final int    rotation = mediaFormat.containsKey(MediaFormat.KEY_ROTATION) ? mediaFormat.getInteger(MediaFormat.KEY_ROTATION) : 0;
      final int    width    = mediaFormat.getInteger(MediaFormat.KEY_WIDTH);
      final int    height   = mediaFormat.getInteger(MediaFormat.KEY_HEIGHT);
      final int    outputWidth;
      final int    outputHeight;

      if (width < height) {
        outputWidth  = thumbnailResolution;
        outputHeight = height * outputWidth / width;
      } else {
        outputHeight = thumbnailResolution;
        outputWidth  = width * outputHeight / height;
      }

      final int outputWidthRotated;
      final int outputHeightRotated;

      if ((rotation % 180 == 90)) {
        //noinspection SuspiciousNameCombination
        outputWidthRotated = outputHeight;
        //noinspection SuspiciousNameCombination
        outputHeightRotated = outputWidth;
      } else {
        outputWidthRotated  = outputWidth;
        outputHeightRotated = outputHeight;
      }

      Log.i(TAG, "video: " + width + "x" + height + " " + rotation);
      Log.i(TAG, "output: " + outputWidthRotated + "x" + outputHeightRotated);

      outputSurface = new OutputSurface(outputWidthRotated, outputHeightRotated, true);

      decoder = MediaCodec.createDecoderByType(mime);
      decoder.configure(mediaFormat, outputSurface.getSurface(), null, 0);
      decoder.start();

      long duration = 0;

      if (mediaFormat.containsKey(MediaFormat.KEY_DURATION)) {
        duration = mediaFormat.getLong(MediaFormat.KEY_DURATION);
      } else {
        Log.w(TAG, "Video is missing duration!");
      }

      callback.durationKnown(duration);

      doExtract(extractor, decoder, outputSurface, outputWidthRotated, outputHeightRotated, duration, thumbnailCount, callback);
    }
  } catch (IOException | TranscodingException e) {
    Log.w(TAG, e);
    callback.failed();
  } finally {
    if (outputSurface != null) {
      outputSurface.release();
    }
    if (decoder != null) {
      decoder.stop();
      decoder.release();
    }
    if (extractor != null) {
      extractor.release();
    }
  }
}
 
Example 16
Source File: VideoUtil.java    From VideoProcessor with Apache License 2.0 4 votes vote down vote up
static long appendVideoTrack(MediaExtractor extractor, MediaMuxer mediaMuxer, int muxerVideoTrackIndex,
                             Integer startTimeUs, Integer endTimeUs, long baseMuxerFrameTimeUs, int bitrate, int iFrameInterval,
                             boolean isFirst, boolean isLast) throws Exception {
    int videoTrack = selectTrack(extractor, false);
    extractor.selectTrack(videoTrack);
    if (startTimeUs == null) {
        startTimeUs = 0;
    }
    extractor.seekTo(startTimeUs, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
    MediaFormat videoFormat = extractor.getTrackFormat(videoTrack);

    //初始化编码器
    int resultWidth = videoFormat.getInteger(MediaFormat.KEY_WIDTH);
    int resultHeight = videoFormat.getInteger(MediaFormat.KEY_HEIGHT);

    AtomicBoolean decodeDone = new AtomicBoolean(false);
    VideoAppendEncodeThread encodeThread = new VideoAppendEncodeThread(extractor, mediaMuxer, bitrate,
            resultWidth, resultHeight, iFrameInterval, videoTrack,
            decodeDone, baseMuxerFrameTimeUs, isFirst, isLast, muxerVideoTrackIndex);
    VideoDecodeThread decodeThread = new VideoDecodeThread(encodeThread, extractor, startTimeUs == null ? null : startTimeUs / 1000,
            endTimeUs == null ? null : endTimeUs / 1000,
            null, null, null, false,videoTrack, decodeDone);
    decodeThread.start();
    encodeThread.start();
    try {
        decodeThread.join();
        encodeThread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    try {
        extractor.release();
    } catch (Exception e2) {
        CL.e(e2);
    }
    if (encodeThread.getException() != null) {
        throw encodeThread.getException();
    } else if (decodeThread.getException() != null) {
        throw decodeThread.getException();
    }
    return encodeThread.getLastFrametimeUs();
}
 
Example 17
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 18
Source File: MainActivity.java    From Android with Apache License 2.0 4 votes vote down vote up
protected boolean process() throws IOException {

        mMediaExtractor = new MediaExtractor();          
        mMediaExtractor.setDataSource(SDCARD_PATH+"/input.mp4");                
                
        int mVideoTrackIndex = -1;
        int framerate = 0;
        for(int i = 0; i < mMediaExtractor.getTrackCount(); i++) {
            MediaFormat format = mMediaExtractor.getTrackFormat(i);
            String mime = format.getString(MediaFormat.KEY_MIME);
            if(!mime.startsWith("video/")) {                
                continue;
            }
            framerate = format.getInteger(MediaFormat.KEY_FRAME_RATE);            
            mMediaExtractor.selectTrack(i);
            mMediaMuxer = new MediaMuxer(SDCARD_PATH+"/ouput.mp4", OutputFormat.MUXER_OUTPUT_MPEG_4);
            mVideoTrackIndex = mMediaMuxer.addTrack(format);  
            mMediaMuxer.start();
        }
        
        if(mMediaMuxer == null) {
            return false;
        }
        
        BufferInfo info = new BufferInfo();
        info.presentationTimeUs = 0;
        ByteBuffer buffer = ByteBuffer.allocate(500*1024);        
        while(true) {
            int sampleSize = mMediaExtractor.readSampleData(buffer, 0);
            if(sampleSize < 0) {
                break;
            }
            mMediaExtractor.advance();
            info.offset = 0;
            info.size = sampleSize;
            info.flags = MediaCodec.BUFFER_FLAG_SYNC_FRAME;        
            info.presentationTimeUs += 1000*1000/framerate;
            mMediaMuxer.writeSampleData(mVideoTrackIndex,buffer,info);
        }

        mMediaExtractor.release();
        
        mMediaMuxer.stop();
        mMediaMuxer.release();
        
        return true;
    }
 
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: DownloadRedditVideoService.java    From Infinity-For-Reddit with GNU Affero General Public License v3.0 4 votes vote down vote up
private boolean muxVideoAndAudio(String videoFilePath, String audioFilePath, String outputFilePath) {
    try {
        File file = new File(outputFilePath);
        file.createNewFile();
        MediaExtractor videoExtractor = new MediaExtractor();
        videoExtractor.setDataSource(videoFilePath);
        MediaExtractor audioExtractor = new MediaExtractor();
        audioExtractor.setDataSource(audioFilePath);
        MediaMuxer muxer = new MediaMuxer(outputFilePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);

        videoExtractor.selectTrack(0);
        MediaFormat videoFormat = videoExtractor.getTrackFormat(0);
        int videoTrack = muxer.addTrack(videoFormat);

        audioExtractor.selectTrack(0);
        MediaFormat audioFormat = audioExtractor.getTrackFormat(0);
        int audioTrack = muxer.addTrack(audioFormat);
        boolean sawEOS = false;
        int offset = 100;
        int sampleSize = 2048 * 1024;
        ByteBuffer videoBuf = ByteBuffer.allocate(sampleSize);
        ByteBuffer audioBuf = ByteBuffer.allocate(sampleSize);
        MediaCodec.BufferInfo videoBufferInfo = new MediaCodec.BufferInfo();
        MediaCodec.BufferInfo audioBufferInfo = new MediaCodec.BufferInfo();

        videoExtractor.seekTo(0, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
        audioExtractor.seekTo(0, MediaExtractor.SEEK_TO_CLOSEST_SYNC);

        muxer.start();

        while (!sawEOS) {
            videoBufferInfo.offset = offset;
            videoBufferInfo.size = videoExtractor.readSampleData(videoBuf, offset);

            if (videoBufferInfo.size < 0 || audioBufferInfo.size < 0) {
                sawEOS = true;
                videoBufferInfo.size = 0;
            } else {
                videoBufferInfo.presentationTimeUs = videoExtractor.getSampleTime();
                videoBufferInfo.flags = videoExtractor.getSampleFlags();
                muxer.writeSampleData(videoTrack, videoBuf, videoBufferInfo);
                videoExtractor.advance();
            }
        }

        boolean sawEOS2 = false;
        while (!sawEOS2) {
            audioBufferInfo.offset = offset;
            audioBufferInfo.size = audioExtractor.readSampleData(audioBuf, offset);

            if (videoBufferInfo.size < 0 || audioBufferInfo.size < 0) {
                sawEOS2 = true;
                audioBufferInfo.size = 0;
            } else {
                audioBufferInfo.presentationTimeUs = audioExtractor.getSampleTime();
                audioBufferInfo.flags = audioExtractor.getSampleFlags();
                muxer.writeSampleData(audioTrack, audioBuf, audioBufferInfo);
                audioExtractor.advance();

            }
        }

        try {
            muxer.stop();
            muxer.release();
        } catch (IllegalStateException ignore) {}
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}