Untitled

mail@pastecode.io avatar
unknown
plain_text
14 days ago
1.9 kB
2
Indexable
Never
import android.content.Context;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.media.MediaMuxer;
import android.net.Uri;
import java.io.IOException;
import java.nio.ByteBuffer;

public class VideoUtils {

    public static void removeAudioFromVideo(Context context, Uri inputUri, String outputPath) throws IOException {
        MediaExtractor extractor = new MediaExtractor();
        extractor.setDataSource(context, inputUri);

        MediaMuxer muxer = new MediaMuxer(outputPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
        int trackCount = extractor.getTrackCount();
        int videoTrackIndex = -1;

        // Select the video track and add it to the muxer
        for (int i = 0; i < trackCount; i++) {
            MediaFormat format = extractor.getTrackFormat(i);
            String mime = format.getString(MediaFormat.KEY_MIME);
            if (mime.startsWith("video/")) {
                videoTrackIndex = muxer.addTrack(format);
                extractor.selectTrack(i);
                break;
            }
        }

        if (videoTrackIndex == -1) {
            throw new RuntimeException("No video track found in " + inputUri.toString());
        }

        muxer.start();

        ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);
        MediaExtractor.BufferInfo bufferInfo = new MediaExtractor.BufferInfo();
        while (true) {
            bufferInfo.offset = 0;
            bufferInfo.size = extractor.readSampleData(buffer, 0);
            if (bufferInfo.size < 0) {
                break;
            }
            bufferInfo.presentationTimeUs = extractor.getSampleTime();
            bufferInfo.flags = extractor.getSampleFlags();
            muxer.writeSampleData(videoTrackIndex, buffer, bufferInfo);
            extractor.advance();
        }

        muxer.stop();
        muxer.release();
        extractor.release();
    }
}
Leave a Comment