使用MediaCodec播放视频

public class MediaCodecPlayer {

    private static final String PATH = "/sdcard/a.mp4";
    private static MediaExtractor mediaExtractor;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static void codec(Surface surface) {
        mediaExtractor = new MediaExtractor();
        MediaCodec mediaCodec = null;
        try {
            mediaExtractor.setDataSource(PATH);
            for (int i = 0; i < mediaExtractor.getTrackCount(); i++) {
                MediaFormat mediaFormat = mediaExtractor.getTrackFormat(i);
                String mime = mediaFormat.getString(MediaFormat.KEY_MIME);
                if (mime.startsWith("video")) {
                    mediaExtractor.selectTrack(i);
                    mediaCodec = MediaCodec.createDecoderByType(mime);
                    mediaCodec.setCallback(callback);
                    mediaCodec.configure(mediaFormat, surface, null, 0);
                    break;
                }
            }
            mediaCodec.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private static MediaCodec.Callback callback = new MediaCodec.Callback() {


        @Override
        public void onInputBufferAvailable(@NonNull MediaCodec codec, int index) {
            ByteBuffer byteBuffer = codec.getInputBuffer(index);
            byteBuffer.clear();
            int sampleSize = mediaExtractor.readSampleData(byteBuffer, 0);
            if (sampleSize < 0) {
                codec.queueInputBuffer(index, 0, sampleSize, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
            } else {
                codec.queueInputBuffer(index, 0, sampleSize, mediaExtractor.getSampleTime(), 0);
                mediaExtractor.advance();
            }
        }

        @Override
        public void onOutputBufferAvailable(@NonNull MediaCodec codec, int index, @NonNull MediaCodec.BufferInfo info) {
            if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
                mediaExtractor.release();
                codec.stop();
                codec.release();
            } else {
                codec.releaseOutputBuffer(index, true);
            }
        }

        @Override
        public void onError(@NonNull MediaCodec codec, @NonNull MediaCodec.CodecException e) {
        }

        @Override
        public void onOutputFormatChanged(@NonNull MediaCodec codec, @NonNull MediaFormat format) {

        }
    };
}

你可能感兴趣的:(使用MediaCodec播放视频)