html5 MediaRecorder 录制视频和音频

1,017 阅读1分钟

通过MediaRecorder录制canvas视频,并添加音频流。记录一下。

var options = {};
if (typeof MediaRecorder.isTypeSupported == 'function') {
    if (MediaRecorder.isTypeSupported('video/webm;codecs=vp8')) {
        options.mimeType = 'video/webm;codecs=vp8';
    } else if (MediaRecorder.isTypeSupported('video/webm;codecs=vp9')) {
        options.mimeType = 'video/webm;codecs=vp9';
    } else if (MediaRecorder.isTypeSupported('video/webm;codecs=h264')) {
        options.mimeType = 'video/webm;codecs=h264';
    }
}

var recorder = {
    chunks: [],
    start: function (options) {
        var canvas = $("canvas")[0]
        if (!canvas) {
            console.info("canvas is needed!")
            return false;
        }
        this.chunks = [];
        this.stream = canvas.captureStream(60);
        this.mediaRecorder = new MediaRecorder(this.stream);
        this.mediaRecorder.onstop = this.stopHandler;
        this.mediaRecorder.ondataavailable = this.dataHandler;

        if (options.music) {
            this.attachAudio(music);
            this.audio.play();
        }
        this.mediaRecorder.start();
        return true;
    },
    stop: function () {
        this.mediaRecorder.stop();
        if (this.audio) {
            this.audio.currentTime = 0;
            this.audio.pause();
        }
    },
    attachAudio: function (music) {
        var audioCtx = new AudioContext();
        // create a stream from our AudioContext
        var dest = audioCtx.createMediaStreamDestination();
        var audioStream = dest.stream;

        this.audio = document.createElement('audio');
        this.audio.crossOrigin = "anonymous";
        this.audio.loop = "loop";
        this.audio.src = music.url;

        // connect our audio element's output to the stream
        var sourceNode = audioCtx.createMediaElementSource(this.audio);
        sourceNode.connect(dest)
        sourceNode.connect(audioCtx.destination);

        this.stream.addTrack(audioStream.getAudioTracks()[0]);
    },
    dataHandler: function (e) {
        recorder.chunks.push(e.data);
    },
    stopHandler: function () {
        if (recorder.chunks.length) {
            var blob = new Blob(recorder.chunks, {type: "video/webm"})
            var downloadUrl = window.URL.createObjectURL(blob);

            var link = document.createElement('a');
            link.style.display = 'none';
            link.href = downloadUrl;
            link.download = 'media.webm';
            link.disabled = false;
            link.click();
        } else {
            console.info("no data saved");
        }
    }
};