从 mp4 中提取音轨并将其保存为可播放的音频文件
Extract audio track from mp4 and save it to a playable audio file
以下代码是我的作品,可以提取音轨并将其保存到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();
}
提取没有re-encoding的音频流:
ffmpeg -i input-video.mp4 -vn -acodec copy output-audio.aac
-vn没有视频。
-acodec copy 说使用已经存在的相同音频流。
阅读输出以查看它是什么编解码器,以设置正确的文件扩展名。
以下代码是我的作品,可以提取音轨并将其保存到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();
}
提取没有re-encoding的音频流:
ffmpeg -i input-video.mp4 -vn -acodec copy output-audio.aac
-vn没有视频。 -acodec copy 说使用已经存在的相同音频流。
阅读输出以查看它是什么编解码器,以设置正确的文件扩展名。