Извлечение аудио из MP4 и сохранение на SD-карту (MediaExtractor)

У меня есть видеофайл mp4 на моей SD-карте. Я хотел бы извлечь звук из видео, а затем сохранить извлеченный звук в виде отдельного файла на SD-карте с помощью MediaExtractor Api. Вот код, который я пробовал:

  MediaExtractor extractor = new MediaExtractor();
  extractor.setDataSource(MEDIA_PATH_To_File_On_SDCARD);
  for (i = 0; i < extractor.getTrackCount(); i++) {
            MediaFormat format = extractor.getTrackFormat(i);
            String mime = format.getString(MediaFormat.KEY_MIME);
            if (mime.startsWith("audio/")) {
                extractor.selectTrack(i);
                decoder = MediaCodec.createDecoderByType(mime);

                if(decoder != null)
                {
                   decoder.configure(format, null, null, 0);
                }

                break;
            }
        }

Застрял здесь, я понятия не имею, как взять выбранную звуковую дорожку и сохранить ее на SD-карту.


person Donnie Ibiyemi    schedule 13.02.2016    source источник


Ответы (2)


взгляните на мой пост Декодирование видео и кодирование снова Mediacodec получает поврежденный файл, где есть пример (только позаботьтесь и об ответе). вам нужно использовать MediaMuxer, вызывать AddTrack для видеодорожки и записывать данные на эту дорожку в мультиплексор после кодирования каждого кадра. Вы также должны добавить дорожку для аудио. Если вам нужен только звук, игнорируйте часть видео и просто сохраняйте данные в мультиплексоре, связанные со звуком. Вы можете увидеть несколько примеров на странице графика, одним из них может быть этот: https://github.com/google/grafika/

Также вы можете найти больше примеров здесь: http://www.bigflake.com/mediacodec/

Спасибо

person Gabriel Bursztyn    schedule 15.02.2016
comment
Спасибо! Попробую, отпишусь как получилось - person Donnie Ibiyemi; 15.02.2016
comment
@donnie эй, я пытаюсь сделать что-то подобное. Не могли бы вы сказать мне, с чего начать, или поделиться фрагментом кода. - person Ayush Bansal; 24.03.2017

Опоздав на вечеринку, это можно сделать, используя MediaExtractor и MediaMuxer Apis вместе. Проверьте рабочий URL-адрес ниже,

/**
     * @param srcPath the path of source video file.
     * @param dstPath the path of destination video file.
     * @param startMs starting time in milliseconds for trimming. Set to
     *            negative if starting from beginning.
     * @param endMs end time for trimming in milliseconds. Set to negative if
     *            no trimming at the end.
     * @param useAudio true if keep the audio track from the source.
     * @param useVideo true if keep the video track from the source.
     * @throws IOException
     */
    @SuppressLint("NewApi")
    public void genVideoUsingMuxer(String srcPath, String dstPath, int startMs, int endMs, boolean useAudio, boolean useVideo) throws IOException {
        // Set up MediaExtractor to read from the source.
        MediaExtractor extractor = new MediaExtractor();
        extractor.setDataSource(srcPath);
        int trackCount = extractor.getTrackCount();
        // Set up MediaMuxer for the destination.
        MediaMuxer muxer;
        muxer = new MediaMuxer(dstPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
        // Set up the tracks and retrieve the max buffer size for selected
        // tracks.
        HashMap<Integer, Integer> indexMap = new HashMap<Integer, Integer>(trackCount);
        int bufferSize = -1;
        for (int i = 0; i < trackCount; i++) {
            MediaFormat format = extractor.getTrackFormat(i);
            String mime = format.getString(MediaFormat.KEY_MIME);
            boolean selectCurrentTrack = false;
            if (mime.startsWith("audio/") && useAudio) {
                selectCurrentTrack = true;
            } else if (mime.startsWith("video/") && useVideo) {
                selectCurrentTrack = true;
            }
            if (selectCurrentTrack) {
                extractor.selectTrack(i);
                int dstIndex = muxer.addTrack(format);
                indexMap.put(i, dstIndex);
                if (format.containsKey(MediaFormat.KEY_MAX_INPUT_SIZE)) {
                    int newSize = format.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE);
                    bufferSize = newSize > bufferSize ? newSize : bufferSize;
                }
            }
        }
        if (bufferSize < 0) {
            bufferSize = DEFAULT_BUFFER_SIZE;
        }
        // Set up the orientation and starting time for extractor.
        MediaMetadataRetriever retrieverSrc = new MediaMetadataRetriever();
        retrieverSrc.setDataSource(srcPath);
        String degreesString = retrieverSrc.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
        if (degreesString != null) {
            int degrees = Integer.parseInt(degreesString);
            if (degrees >= 0) {
                muxer.setOrientationHint(degrees);
            }
        }
        if (startMs > 0) {
            extractor.seekTo(startMs * 1000, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
        }
        // Copy the samples from MediaExtractor to MediaMuxer. We will loop
        // for copying each sample and stop when we get to the end of the source
        // file or exceed the end time of the trimming.
        int offset = 0;
        int trackIndex = -1;
        ByteBuffer dstBuf = ByteBuffer.allocate(bufferSize);
        MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
        muxer.start();
        while (true) {
            bufferInfo.offset = offset;
            bufferInfo.size = extractor.readSampleData(dstBuf, offset);
            if (bufferInfo.size < 0) {
                Log.d(TAG, "Saw input EOS.");
                bufferInfo.size = 0;
                break;
            } else {
                bufferInfo.presentationTimeUs = extractor.getSampleTime();
                if (endMs > 0 && bufferInfo.presentationTimeUs > (endMs * 1000)) {
                    Log.d(TAG, "The current sample is over the trim end time.");
                    break;
                } else {
                    bufferInfo.flags = extractor.getSampleFlags();
                    trackIndex = extractor.getSampleTrackIndex();
                    muxer.writeSampleData(indexMap.get(trackIndex), dstBuf, bufferInfo);
                    extractor.advance();
                }
            }
        }
        muxer.stop();
        muxer.release();
        return;
    }

Вы можете использовать вышеупомянутый метод, используя одну строку: genVideoUsingMuxer(videoFile, originalAudio, -1, -1, true, false)

Кроме того, прочитайте комментарии, чтобы использовать этот метод более эффективно. GIST: https://gist.github.com/ArsalRaza/132a6e99d59aa80b9861ae368bc786d0

person Arsal Imam    schedule 02.11.2018