在本教學中,您將學習如何使用 JavaScript MediaRecorder API 建立音訊和視訊錄製器。所以這可以使用 WebRTC 來完成。
WebRTC 是即時通訊的簡稱。我們可以存取並捕獲用戶設備中可用的網路攝影機和麥克風設備。
我們可以使用 ECMAScript 物件存取使用者裝置的網路攝影機和麥克風
navigator.mediaDevices.getUserMedia(constraints).
因此,getUserMedia 函數預設會尋求使用者許可以使用您的網路攝影機。此函數會傳回一個promise,一旦您按一下「確定」並表示同意,該函數就會被觸發並在您的系統中啟用網路攝影機,否則,如果您不允許,那麼它還有一個catch 方法這會關閉網路攝影機。
我們也可以向函數 getUserMedia() 函數傳遞一個參數,這可能就像我們想要某個特定寬度或高度的圖片一樣。
我們的前端部分將包含以下元素 -
對於視訊錄製畫面將有一些元素,例如 -
將顯示視訊媒體螢幕的視訊元素
開始按鈕將開始錄影
停止按鈕將停止視訊錄製串流。
對於音訊錄製,它將有兩個按鈕
開始按鈕將開始錄音
#停止按鈕將停止音訊錄製串流。
我們將添加 font Awesome CDN 以添加開始和停止按鈕圖標,為了使頁面更具吸引力,我們將在元素上添加 CSS 樣式。
<!DOCTYPE html> <html> <head> <title>Video & Audio Recorder</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> body { text-align: center; color: red; font-size: 1.2em; } /* styling of start and stop buttons */ #video_st, #video_en, #aud_st, #aud_en{ margin-top: 10px; padding: 10px; border-radius: 4px; cursor: pointer; } #vidBox{ background-color: grey; } /*video box styling*/ video { background-color: gray; display: block; margin: 6px auto; width: 520px; height: 240px; } /*audio box styling*/ audio { display: block; margin: 6px auto; } a { color: green; } </style> </head> <body> <h1 style="color:blue"> Video-Audio recorder</h1> <div class="display-none" id="vid-recorder"> <h3>Record Video </h3> <video autoplay id="vidBox"> </video> <!-- click this button to start video recording --> <button type="button" id="video_st" onclick="start_video_Recording()"> <i class="fa fa-play"></i></button> <!-- click this button to stop video recording --> <button type="button" id="video_en" disabled onclick="stop_Recording(this, document.getElementById('video_st'))"> <i class="fa fa-stop"></i> </button> </div> <!-- ------------ --> <br> <hr> <!-- ------------ --> <div class="display-none" id="audio_rec"> <h3> Record Audio</h3> <!-- click this button to start audio recording --> <button type="button" id="aud_st" onclick="start_audio_Recording()"><i class="fa fa-play"></i> </button> <!-- click this button to stop video recording --> <button type="button" id="aud_en"disabled onclick="stop_Recording(this, document.getElementById('aud_st'))"> <i class="fa fa-stop"></i></button> </div> </body> </html>
當您點擊「開始影片」按鈕時,它將呼叫start_video_Recording()函數,而「停止」按鈕將呼叫stop_Recording () 類似地,對於音頻,單擊開始按鈕將觸發函數start_audio_Recording() ,對於停止按鈕stop_Recording() 函數將被呼叫。
讓我們定義一個函數來啟動影片並錄製它。
function start_video_Recording() { // stores the recorded media let chunksArr= []; const startBtn=document.getElementById("video_st"); const endBtn=document.getElementById("video_en"); // permission to access camera and microphone navigator.mediaDevices.getUserMedia({audio: true, video: true}) .then((mediaStreamObj) => { // Create a new MediaRecorder instance const medRec =new MediaRecorder(mediaStreamObj); window.mediaStream = mediaStreamObj; window.mediaRecorder = medRec; medRec.start(); //when recorded data is available then push into chunkArr array medRec.ondataavailable = (e) => {chunksArr.push(e.data);}; //stop the video recording medRec.onstop = () => { const blobFile = new Blob(chunksArr, { type:"video/mp4" }); chunksArr= []; // create video element and store the media which is recorded const recMediaFile = document.createElement("video"); recMediaFile.controls = true; const RecUrl = URL.createObjectURL(blobFile); //keep the recorded url as source recMediaFile.src = RecUrl; document.getElementById(`vid-recorder`).append(recMediaFile); }; document.getElementById("vidBox").srcObject = mediaStreamObj; //disable the start button and enable the stop button startBtn.disabled = true; endBtn.disabled = false; }); }
當按下開始按鈕時,它將呼叫上述函數,這將觸發 WebRTC 相機和麥克風方法來取得錄製權限,並將啟用停止錄製按鈕並停用開始錄製按鈕。
當按下停止按鈕時,它將呼叫 stop() 函數並停止所有媒體串流軌道。
然後為了記錄媒體串流,我們將建立一個媒體記錄器實例並使媒體串流以及媒體重新排序全域。然後停止視訊將停止媒體串流,創建視訊元素將創建一個新的視訊元素並儲存錄製的媒體資料。
同樣,start_audio_Recording() 函數也與 start_video_Recording() 函數類似,但需要進行一些更改。
現在讓我們定義一個函數來停止錄製。
function stop_Recording(end, start) { window.mediaRecorder.stop(); // stop all tracks window.mediaStream.getTracks() .forEach((track) => {track.stop();}); //disable the stop button and enable the start button end.disabled = true; start.disabled = false; }
此函數將停止儲存在媒體串流中的所有媒體軌道。
讓我們將上述函數加入到 HTML 程式碼中,以實現視訊和音訊錄製功能。
<!DOCTYPE html> <html> <head> <title>Video & Audio Recorder</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> body { text-align: center; color: red; font-size: 1.2em; } //video start & end, Audio start & end button styling #video_st, #video_en, #aud_st, #aud_en{ margin-top: 10px; padding: 10px; border-radius: 4px; cursor: pointer; } #vidBox{ background-color: grey; } video { background-color: gray; display: block; margin: 6px auto; width: 420px; height: 240px; } audio { display: block; margin: 6px auto; } a { color: green; } </style> </head> <body> <h1 style="color:blue"> Video-Audio recorder</h1> <div class="display-none" id="vid-recorder"> <h3>Record Video </h3> <video autoplay id="vidBox"> </video> <button type="button" id="video_st" onclick="start_video_Recording()"> <i class="fa fa-play"></i></button> <button type="button" id="video_en" disabled onclick="stop_Recording(this, document.getElementById('video_st'))"> <i class="fa fa-stop"></i> </button> </div> <!-- ------------ --> <br> <hr> <!-- ------------ --> <div class="display-none" id="audio_rec"> <h3> Record Audio</h3> <button type="button" id="aud_st" onclick="start_audio_Recording()"><i class="fa fa-play"></i> </button> <button type="button" id="aud_en" disabled onclick="stop_Recording(this, document.getElementById('aud_st'))"> <i class="fa fa-stop"></i></button> </div> <script> //----------------------Video------------------------------------- function start_video_Recording() { //To stores the recorded media let chunks = []; const startBtn=document.getElementById("video_st"); const endBtn=document.getElementById("video_en"); // Access the camera and microphone navigator.mediaDevices.getUserMedia({audio: true, video: true}) .then((mediaStreamObj) => { // Create a new MediaRecorder instance const medRec =new MediaRecorder(mediaStreamObj); window.mediaStream = mediaStreamObj; window.mediaRecorder = medRec; medRec.start(); //when recorded data is available then push into chunkArr array medRec.ondataavailable = (e) => { chunks.push(e.data); }; //stop the video recording medRec.onstop = () => { const blobFile = new Blob(chunks, { type:"video/mp4" });chunks = []; // create video element and store the media which is recorded const recMediaFile = document.createElement("video"); recMediaFile.controls = true; const RecUrl = URL.createObjectURL(blobFile); //keep the recorded url as source recMediaFile.src = RecUrl; document.getElementById(`vid-recorder`).append(recMediaFile); }; document.getElementById("vidBox").srcObject = mediaStreamObj; startBtn.disabled = true; endBtn.disabled = false; }); } //--------------------audio--------------------------------------- function start_audio_Recording() { //To stores the recorded media let chunksArr = []; const startBtn=document.getElementById("aud_st"); const endBtn=document.getElementById("aud_en"); // Access the camera and microphone navigator.mediaDevices.getUserMedia({audio: true, video: false}) .then((mediaStream) => { const medRec = new MediaRecorder(mediaStream); window.mediaStream = mediaStream; window.mediaRecorder = medRec; medRec.start(); //when recorded data is available then push into chunkArr array medRec.ondataavailable = (e) => { chunksArr.push(e.data); }; //stop the audio recording medRec.onstop = () => { const blob = new Blob(chunksArr, {type: "audio/mpeg"}); chunksArr = []; // create audio element and store the media which is recorded const recMediaFile = document.createElement("audio"); recMediaFile.controls = true; const RecUrl = URL.createObjectURL(blob); recMediaFile.src = RecUrl; document.getElementById(`audio_rec`).append( recMediaFile); }; startBtn.disabled = true; endBtn.disabled = false; }); } function stop_Recording(end, start) { //stop all tracks window.mediaRecorder.stop(); window.mediaStream.getTracks() .forEach((track) => {track.stop();}); //disable the stop button and enable the start button end.disabled = true; start.disabled = false; } </script> </body> </html>
從輸出可以看出,當點擊影片開始按鈕時,它會呼叫start_video_Recording() 函數,並在該函數中呼叫navigator.mediaDevices.getUserMedia() 方法,並開啟一個權限選單,用於尋找視訊和麥克風權限。它傳回一個解析媒體流的承諾。在接收到音訊或視訊媒體串流後,它會建立一個媒體記錄器的實例,並透過呼叫上述程式碼中的函數 medRec.start() 來開始記錄。
因此,您將了解使用 WebRTC 建立視訊和音訊錄製的完整過程。
以上是如何使用 JavaScript MediaRecorder API 建立視訊和音訊錄製器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!