簡體   English   中英

從 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();
            }

要在不重新編碼的情況下提取音頻流:

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

-vn 不是視頻。 -acodec copy 表示使用已經存在的相同音頻流。

閱讀輸出以查看它是什么編解碼器,以設置正確的文件擴展名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM