JavaScript實現音視頻錄制

帶有聲音的視頻錄制
<!DOCTYPE html>
<html lang="zh-cmn">
<head>
    <meta charset="utf-8">
    <style type="text/css">
        body {
            padding: 0;
            margin: 0;
        }

        svg:not(:root) {
            display: block;
        }

        .playable-code {
            background-color: #f4f7f8;
            border: none;
            border-left: 6px solid #558abb;
            /*border-width: medium medium medium 6px;*/
            color: #4d4e53;
            height: 100px;
            width: 90%;
            padding: 10px 10px 0;
        }

        .playable-canvas {
            border: 1px solid #4d4e53;
            border-radius: 2px;
        }

        .playable-buttons {
            text-align: right;
            width: 90%;
            padding: 5px 10px 5px 26px;
        }
    </style>

    <style type="text/css">
        body {
            font: 14px "Open Sans", "Arial", sans-serif;
        }

        video {
            margin-top: 2px;
            border: 1px solid black;
        }

        .button {
            cursor: pointer;
            display: inline-block;
            width: 80px;
            border: 1px solid black;
            font-size: 16px;
            text-align: center;
            padding-top: 2px;
            padding-bottom: 4px;
            color: white;
            background-color: darkgreen;
            text-decoration: none;
            margin-left: 20px;
        }

        h2 {
            margin-bottom: 4px;
        }

        .left {
            margin-right: 10px;
            float: left;
            padding: 0;
        }

        .right {
            margin-left: 10px;
            float: left;
            width: 160px;
            padding: 0;
        }

        .bottom {
            clear: both;
            padding-top: 10px;
        }

        .hide {
            display: none;
        }
    </style>

    <title>Recording a media element - Example - code sample</title>
</head>
<body>
<br>

<div class="left">
    <video id="preview" width="640" height="480" autoplay muted poster="https://dss2.bdstatic.com/6Ot1bjeh1BF3odCf/it/u=1944450624,2456318320&fm=85&app=79&f=JPEG?w=121&h=75&s=0DE6CD1393B06D805451B0D6000080B1"> </video>
    <video id="recording" class="hide" width="640" height="480" controls> </video>
    <div>
        <span id="startButton" class="button">
            錄制
        </span>
        <span id="stopButton" class="button hide">
            停止
        </span>
        <a id="downloadButton" class="button hide">
            下載
        </a>
    </div>
</div>

<div class="bottom">
    <span id="timestamp">
        00:00
    </span> / 1:00
    <pre id="log">

    </pre>
</div>


<script>
    let preview = document.getElementById("preview");
    let recording = document.getElementById("recording");
    let startButton = document.getElementById("startButton");
    let stopButton = document.getElementById("stopButton");
    let downloadButton = document.getElementById("downloadButton");
    let logElement = document.getElementById("log");
    let timestamp = document.getElementById("timestamp");

    let recordingTimeMS = 1 * 60 * 1000;  // 1min

    let recorder;
    let intervalId = null;
    let record_status = false;  // 是否正在錄制

    function configUi(operator_type) {
        if (operator_type === 'start') {
            timestamp.innerText = `00:00`;
            record_status = true;
            let timeStamp = 1;
            intervalId = setInterval(() => {
                const min = Math.floor(timeStamp / 60);
                const sec = timeStamp % 60;
                timestamp.innerText = `${min > 9 ? min : ("0" + min)}:${sec > 10 ? sec : ("0" + sec)}`;
                timeStamp += 1;
            }, 1000);
            removeClass(preview, 'hide');  // 預覽的顯示
            addClass(recording, 'hide');  // 播放的隱藏
            addClass(startButton, 'hide');  // 開始按鈕隱藏
            removeClass(stopButton, 'hide');  // 結束按鈕顯示
        } else {
            if (record_status === true) {
                record_status = false;
                intervalId && clearInterval(intervalId);
                addClass(preview, 'hide');  // 預覽的隱藏
                removeClass(recording, 'hide');  // 播放的顯示
                removeClass(startButton, 'hide');  // 開始按鈕顯示
                removeClass(downloadButton, 'hide');  // 下載按鈕顯示
                addClass(stopButton, 'hide');  // 結束按鈕隱藏
            }
        }
        return true;
    }

    function addClass(ele, className) {
        ele.classList.add(className);
    }

    function removeClass(ele, className) {
        ele.classList.remove(className);
    }

    function log(msg) {
        logElement.innerHTML += msg + "\n";
    }

    function wait(delayInMS) {
        return new Promise(resolve => setTimeout(resolve, delayInMS));
    }

    function startRecording(stream, lengthInMS) {
        recorder = new MediaRecorder(stream);
        let data = [];

        recorder.ondataavailable = event => data.push(event.data);
        recorder.start();
        log(recorder.state + " for " + (lengthInMS / 1000) + " seconds...");

        let stopped = new Promise((resolve, reject) => {
            recorder.onstop = resolve;
            recorder.onerror = event => reject(event.name);
        });

        let recorded = wait(lengthInMS).then(() => {
                return recorder.state === "recording" && configUi("stop") && recorder.stop();
            }
        );

        return Promise.all([
            stopped
            // recorded
        ])
            .then(() => data);
    }

    function stop(stream) {
        configUi('stop');
        stream.getTracks().forEach(track => track.stop());
        recorder.state === "recording" && recorder.stop();
    }

    startButton.addEventListener("click", function () {
        navigator.mediaDevices.getUserMedia({
            video: true,
            audio: true
        }).then(stream => {
            configUi("start");
            preview.srcObject = stream;
            downloadButton.href = stream;
            preview.captureStream = preview.captureStream || preview.mozCaptureStream;
            return new Promise(resolve => preview.onplaying = resolve);
        }).then(() => startRecording(preview.captureStream(), recordingTimeMS))
            .then(recordedChunks => {
                console.log(recordedChunks);
                let recordedBlob = new Blob(recordedChunks, {type: "video/webm"});
                recording.src = URL.createObjectURL(recordedBlob);
                downloadButton.href = recording.src;
                downloadButton.download = "RecordedVideo.webm";
                log("Successfully recorded " + recordedBlob.size + " bytes of " +
                    recordedBlob.type + " media.");
            })
            .catch(log);
    }, false);

    stopButton.addEventListener("click", function () {
        stop(preview.srcObject);
    }, false);

</script>

</body>
</html>
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容