Search code examples
androidandroid-sdcardandroid-mediacodecmediamuxermediaextractor

Extract Audio from Mp4 and Save to Sd Card (MediaExtractor)


I have a mp4 video file in my sd card. I would like to extract the audio from the video and then save the extracted audio as a separate file on the sd card using MediaExtractor Api. Here is the code I've tried:

  MediaExtractor extractor = new MediaExtractor();
  extractor.setDataSource(MEDIA_PATH_To_File_On_SDCARD);
  for (i = 0; i < extractor.getTrackCount(); i++) {
            MediaFormat format = extractor.getTrackFormat(i);
            String mime = format.getString(MediaFormat.KEY_MIME);
            if (mime.startsWith("audio/")) {
                extractor.selectTrack(i);
                decoder = MediaCodec.createDecoderByType(mime);

                if(decoder != null)
                {
                   decoder.configure(format, null, null, 0);
                }

                break;
            }
        }

Am stuck here I have no idea of how to take the selected audio track and save it to the sd card.


Solution

  • take a look at my post Decoding Video and Encoding again by Mediacodec gets a corrupted file where there is an example (just take care about the answer too). you have to use a MediaMuxer, call AddTrack for the video track and write the data to this track to the muxer after encoding each frame. You have to add track for audio too. If you just want only audio, ignore the video part, and just save the data to the muxer related to the audio. You can see some examples in grafika page, one of them could be this: https://github.com/google/grafika/

    Also you can find more examples here: http://www.bigflake.com/mediacodec/

    Thanks