Reputation: 121
The following code is my work which can extract the audio track and save it to a file in android. However, I don't know how to encode the audio track to be a playable audio file (e.g., .m4a or .aac). In addition, I also read the format information of the audio track {mime=audio/mp4a-latm, aac-profile=2, channel-count=2, track-id=2, profile=2, max-input-size=610, durationUs=183600181, csd-0=java.nio.HeapByteBuffer[pos=0 lim=2 cap=2], sample-rate=44100}.
MediaExtractor extractor = new MediaExtractor();
try
{
extractor.setDataSource("input.mp4");
int numTracks = extractor.getTrackCount();
int audioTrackIndex = -1;
for (int i = 0; i < numTracks; ++i)
{
MediaFormat format = extractor.getTrackFormat(i);
String mime = format.getString(MediaFormat.KEY_MIME);
if (mime.equals("audio/mp4a-latm"))
{
audioTrackIndex = i;
break;
}
}
// Extract audio
if (audioTrackIndex >= 0)
{
ByteBuffer byteBuffer = ByteBuffer.allocate(500 * 1024);
File audioFile = new File("output_audio_track");
FileOutputStream audioOutputStream = new FileOutputStream(audioFile);
extractor.selectTrack(audioTrackIndex);
while (true)
{
int readSampleCount = extractor.readSampleData(byteBuffer, 0);
if (readSampleCount < 0)
{
break;
}
// Save audio file
byte[] buffer = new byte[readSampleCount];
byteBuffer.get(buffer);
audioOutputStream.write(buffer);
byteBuffer.clear();
extractor.advance();
}
audioOutputStream.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
extractor.release();
}
Upvotes: 2
Views: 1782
Reputation: 46
To extract the audio stream without re-encoding:
ffmpeg -i input-video.mp4 -vn -acodec copy output-audio.aac
-vn is no video. -acodec copy says use the same audio stream that's already in there.
Read the output to see what codec it is, to set the right filename extension.
Upvotes: 3