html5 MediaRecorder 录制视频和音频

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

定义canvas变化逻辑,比如每秒写一次图表

比如用echarts,定时写入cavans,做成动画效果,并录制。

测试代码

录制代码,通过播放音频添加背景音乐


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");
        }
    }
};

 

你可能感兴趣的:(Web,APIs)