从mp4中提取音轨并将其保存为可播放的音频文件

时间:2017-04-18 11:35:54

标签: java android audio mediaextractor

以下代码是我的工作,它可以提取音轨并将其保存到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],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();
            }

1 个答案:

答案 0 :(得分:3)

要提取音频流而无需重新编码:

ffmpeg -i input-video.mp4 -vn -acodec复制output-audio.aac

-vn没有视频。 -acodec复制说使用那里已经存在的相同音频流。

读取输出以查看它是什么编解码器,以设置正确的文件扩展名。