Web網頁音視頻通話之Webrtc相關操作(一)

目錄

  • 打開攝像頭/關閉攝像頭
  • 靜音/解除靜音
  • 打開視頻/關閉視頻
  • 截圖且下載

打開攝像頭/關閉攝像頭

效果圖

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>打開攝像頭</title>
    <link rel="stylesheet" href="../../../static/layui/css/layui.css">
</head>
<body>
<div id="container">
    <div class="layui-row">
        <div class="layui-col-xs6 layui-col-md12" style="text-align: center">
            <video id="video-local" autoplay playsinline width="400px" height="400px"></video>
        </div>
    </div>
    <div class="layui-row">
        <div class="layui-col-xs6 layui-col-md12" style="text-align: center">
            <button type="button" class="layui-btn layui-btn-normal" onclick="openCamera()">打開攝像頭</button>
            <button type="button" class="layui-btn layui-btn-danger" onclick="stopVideo()">關閉攝像頭</button>
        </div>
    </div>
    <blockquote class="layui-elem-quote layui-text" style="margin-top: 15px;">
        <p>顯示攝像頭預覽的內容,網頁上由元素video來呈現。</p>
        <p>點擊打開攝像頭按鈕後,瀏覽器會詢問是否允許,請點擊“允許”。</p>
    </blockquote>
</div>
</body>
</html>

javaScript

   let videoElem = document.querySelector('video');

    /**
     * MediaDevices.getUserMedia()方法在用戶允許後,按照請求,拿到stream。 stream可以包含視頻或音頻。前面的設定裏,我們只使用視頻。
     * 如果用戶拒絕了使用攝像頭申請,或者申請的媒體不可用,即表現爲被拒絕。 用戶拒絕會報NotAllowedError,找不到符合要求的設備會報NotFoundError DOMException。
     * @param e
     * @returns {Promise<void>}
     */
    function openCamera() {
        if (window.stream != null) {
            alert('攝像頭已打開,請勿重新打開攝像頭');
            return false;
        }
        const constraints = {
            audio: true,
            video: true
        };
        navigator.mediaDevices.getUserMedia(constraints).then(gotStream).catch(error => {
            console.error(error)
        });
    }

    /**
     * 成功獲取到流
     * @param stream
     */
    function gotStream(stream) {
        window.stream = stream;
        videoEle.srcObject = stream;
    }

    /**
     *  關閉攝像頭
     *  獲取到video中的流,並將流中的軌道關閉
     */
    function stopVideo() {
        // 獲取video中的流
        const stream = videoElem.srcObject;
        // 判斷stream 是否爲空
        if (stream == null) {
            return;
        }
        // 獲取流中的所有軌道
        const tracks = stream.getTracks();
        tracks.forEach(function (track) {
            track.stop();
        });
        videoElem.srcObject = null;
        window.stream = null;
    }

靜音/解除靜音

效果圖

前端代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>靜音-解除靜音</title>
    <link rel="stylesheet" href="../../../static/layui/css/layui.css">
</head>
<body>
<div id="container">
    <div class="layui-row">
        <div class="layui-col-xs6 layui-col-md12" style="text-align: center">
            <video id="video-local" autoplay playsinline width="400px" height="400px"></video>
        </div>
    </div>
    <div class="layui-row">
        <div class="layui-col-xs6 layui-col-md12" style="text-align: center">
            <button type="button" class="layui-btn layui-btn-normal" onclick="openCamera()">打開攝像頭</button>
            <button id="mute" type="button" class="layui-btn layui-btn-normal" onclick="muted()">靜音</button>
            <button id="unmute" type="button" class="layui-btn layui-btn-normal" onclick="unmuted()">解除靜音</button>
        </div>
    </div>
    <blockquote class="layui-elem-quote layui-text" style="margin-top: 15px;">
        <p>1.顯示攝像頭預覽的內容,網頁上由元素video來呈現。</p>
        <p>2.點擊打開攝像頭按鈕後,瀏覽器會詢問是否允許,請點擊“允許”。</p>
        <p>3.打開攝像頭獲取到瀏覽器攝像頭數據後,可以對獲取到的流數據進行靜音以及解除靜音相關操作</p>
    </blockquote>
</div>
</body>
</html>

javaScript

    const constraints = {
        audio: true,
        video: true
    };

    let localStream = null;
    let videoEle = document.querySelector('video');
    /**
     * MediaDevices.getUserMedia()方法在用戶允許後,按照請求,拿到stream。 stream可以包含視頻或音頻。前面的設定裏,我們只使用視頻。
     * 如果用戶拒絕了使用攝像頭申請,或者申請的媒體不可用,即表現爲被拒絕。 用戶拒絕會報NotAllowedError,找不到符合要求的設備會報NotFoundError DOMException。
     * @param e
     * @returns {Promise<void>}
     */
     function openCamera() {
        if(localStream!=null){
            alert('攝像頭已打開,請勿重新打開攝像頭');
            return false;
        }
         navigator.mediaDevices.getUserMedia(constraints).then(stream=>{
            localStream = stream;
            videoEle.srcObject = stream;
        }).catch(error=>{
            alert('打開攝像頭失敗');
            console.error('打開攝像頭失敗',error)
        });
    }

    function muted() {
        if(localStream==null){
            alert('請打開音視頻');
            return false;
        }
        const tracks = localStream.getTracks();
        tracks.forEach(track => {
            if(track.kind === 'audio'){
                track.enabled = false
            }
            console.log(track)
        });
        alert('靜音開啓,u can`t speak ')
    }

    function unmuted() {
        if(localStream==null){
            alert('請打開音視頻');
            return false;
        }
        const tracks = localStream.getTracks();
        tracks.forEach(track => {
            if(track.kind === 'audio'){
                track.enabled = true
            }
            console.log(track)
        });
        alert('解除靜音,u can speak ')
    }
}

打開視頻/關閉視頻

效果圖

前端代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>打開視頻/關閉視頻</title>
    <link rel="stylesheet" href="../../../static/layui/css/layui.css">
</head>
<body>
<div id="container">
    <div class="layui-row">
        <div class="layui-col-xs6 layui-col-md12" style="text-align: center">
            <video id="video-local" autoplay playsinline width="400px" height="400px"></video>
        </div>
    </div>
    <div class="layui-row">
        <div class="layui-col-xs6 layui-col-md12" style="text-align: center">
            <button type="button" class="layui-btn layui-btn-normal" onclick="openCamera()">打開攝像頭</button>
            <button id="openVideo"  type="button" class="layui-btn layui-btn-normal" onclick="openVideo()">打開視頻</button>
            <button id="closeVideo"  type="button" class="layui-btn layui-btn-normal" onclick="closeVideo()">關閉視頻</button>
        </div>
    </div>
    <blockquote class="layui-elem-quote layui-text" style="margin-top: 15px;">
        <p>1.顯示攝像頭預覽的內容,網頁上由元素video來呈現。</p>
        <p>2.點擊打開攝像頭按鈕後,瀏覽器會詢問是否允許,請點擊“允許”。</p>
        <p>3.打開攝像頭獲取到瀏覽器攝像頭數據後,可以對獲取到的流數據進行打開視頻/關閉視頻相關操作</p>
    </blockquote>
</div>

</body>
</html>

javaScript

 const constraints = {
        audio: true,
        video: true
    };

    let localStream = null;
    let videoEle = document.querySelector('video');
    /**
     * MediaDevices.getUserMedia()方法在用戶允許後,按照請求,拿到stream。 stream可以包含視頻或音頻。前面的設定裏,我們只使用視頻。
     * 如果用戶拒絕了使用攝像頭申請,或者申請的媒體不可用,即表現爲被拒絕。 用戶拒絕會報NotAllowedError,找不到符合要求的設備會報NotFoundError DOMException。
     * @param e
     * @returns {Promise<void>}
     */
     function openCamera() {
        if(localStream!=null){
            alert('攝像頭已打開,請勿重新打開攝像頭');
            return false;
        }
         navigator.mediaDevices.getUserMedia(constraints).then(stream=>{
            localStream = stream;
            videoEle.srcObject = stream;
        }).catch(error=>{
            alert('打開攝像頭失敗');
            console.error('打開攝像頭失敗',error)
        });
    }

    function openVideo() {
        if(localStream==null){
            alert('請打開音視頻');
            return false;
        }
        const tracks = localStream.getTracks();
        tracks.forEach(track => {
            if(track.kind === 'video'){
                track.enabled = true
            }
            console.log(track)
        });
        alert('打開視頻,u can see u ')
    }

    function closeVideo() {
        if(localStream==null){
            alert('請打開音視頻');
            return false;
        }
        const tracks = localStream.getTracks();
        tracks.forEach(track => {
            if(track.kind === 'video'){
                track.enabled = false
            }
            console.log(track)
        });
        alert('關閉視頻,u can`t see u ')
    }

視頻截圖

效果圖

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>截屏</title>
    <link rel="stylesheet" href="../../../static/layui/css/layui.css">

</head>
<body>
<div id="container">
    <div class="layui-row">
        <div class="layui-col-xs6 layui-col-md12" style="text-align: center">
            <video id="video-local" autoplay playsinline width="400px" height="400px"></video>
        </div>
    </div>
    <div class="layui-row">
        <div class="layui-col-xs6 layui-col-md12" style="text-align: center">
            <button type="button" class="layui-btn layui-btn-normal" onclick="openCamera()">打開攝像頭</button>
            <button type="button" class="layui-btn layui-btn-normal" onclick="getCapure()">截圖</button>
        </div>
    </div>
    <canvas id="mainCanvas"></canvas>
    <div id="list" style="display: grid; grid-template-columns: repeat(auto-fill, 100px);
    column-gap: 20px; row-gap: 20px;"></div>
    <blockquote class="layui-elem-quote layui-text" style="margin-top: 15px;">
        <p>1.獲取攝像頭數據,點擊截圖,展示截圖數據</p>
    </blockquote>
</div>
</body>
</html>

javaScript

 const video = document.querySelector('video');
    const constraints = {
        audio: false,
        video: true
    };

    const list = document.querySelector('#list'); // 拿來存放多個元素

    function openCamera() {
        navigator.mediaDevices.getUserMedia(constraints).then(gotStream).catch(onError);
    }

    /**
     * 成功獲取流數據
     * @param stream
     */
    function gotStream(stream) {
        window.stream = stream;
        video.srcObject = stream;
    }
    /**
     * 獲取流發生錯誤
     * @param stream
     */
    function onError(error) {
        console.log('navigator.MediaDevices.getUserMedia error: ', error.message, error.name);
    }

    /**
     * 捕獲
     */
    function getCapure(){
        const mCanvas = window.canvas = document.querySelector('#mainCanvas');
        mCanvas.width = 480;
        mCanvas.height = 360;

        // 開始截取
        mCanvas.width = video.videoWidth;
        mCanvas.height = video.videoHeight;
        mCanvas.getContext('2d').drawImage(video, 0, 0, mCanvas.width, mCanvas.height);
        // 新增1張
        var divItem = document.createElement("div");
        divItem.style.display = "block";
        divItem.width = 100;
        divItem.height = divItem.width * video.videoHeight / video.videoWidth; // 計算一下比例
        divItem.style.width = divItem.width + "px";
        divItem.style.height = divItem.height + "px";
        var c1 = document.createElement("canvas");
        c1.width = divItem.width;
        c1.height = divItem.height;
        c1.getContext('2d').drawImage(video, 0, 0, mCanvas.width, mCanvas.height, 0, 0, c1.width, c1.height);
        divItem.appendChild(c1);
        list.appendChild(divItem);
    }

    /**
     * 清除記錄
     */
    function clear(){
        var child = list.lastElementChild;
        while (child) {
            list.removeChild(child);
            child = list.lastElementChild;
        }
    }

寫在最後學習參考視頻講解比較詳細:https://space.bilibili.com/394612055/video?tid=0&page=2&keyword=&order=pubdate

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章