【问题标题】:Extract audio track from mp4 and save it to a playable audio file从 mp4 中提取音轨并将其保存到可播放的音频文件中
【发布时间】:2017-09-14 05:26:44
【问题描述】:

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

【问题讨论】:

  • 尝试 this answer 将您的 AudioOutputStream 保存为 WAV 文件。
  • AFAIK 无法播放 aac 原始流。您必须添加每个帧所需的元数据。

标签: java android audio mediaextractor


【解决方案1】:

提取音频流而不重新编码:

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

-vn 不是视频。 -acodec 副本说使用已经存在的相同音频流。

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

【讨论】:

    猜你喜欢
    • 2016-05-24
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 2015-05-14
    • 2014-10-26
    • 2019-11-26
    • 2017-06-20
    • 1970-01-01
    相关资源
    最近更新 更多