以下代码是我的工作,它可以提取音轨并将其保存到 android 中的文件中。但是,我不知道如何将音轨编码为可播放的音频文件(例如,.m4a 或 .aac)。另外我还读取了音轨的格式信息 {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],采样率=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();
}