在本教程中,您將學(xué)習(xí)如何使用 JavaScript MediaRecorder API 創(chuàng)建音頻和視頻錄制器。所以這可以使用 WebRTC 來完成。
什么是 WebRTC?
WebRTC 是實時通信的簡稱。我們可以訪問并捕獲用戶設(shè)備中可用的網(wǎng)絡(luò)攝像頭和麥克風(fēng)設(shè)備。
我們可以使用 ECMAScript 對象訪問用戶設(shè)備的網(wǎng)絡(luò)攝像頭和麥克風(fēng)
navigator.mediaDevices.getUserMedia(constraints).
登錄后復(fù)制
因此,getUserMedia 函數(shù)默認(rèn)情況下會尋求用戶許可以使用您的網(wǎng)絡(luò)攝像頭。此函數(shù)返回一個 promise,一旦您單擊“確定”并表示同意,該函數(shù)就會被觸發(fā)并在您的系統(tǒng)中啟用網(wǎng)絡(luò)攝像頭,否則,如果您不允許,那么它還有一個 catch 方法這會關(guān)閉網(wǎng)絡(luò)攝像頭。
我們還可以向函數(shù) getUserMedia() 函數(shù)傳遞一個參數(shù),這可能就像我們想要某個特定寬度或高度的圖片一樣。
前端設(shè)計
我們的前端部分將包含如下元素 –
對于視頻錄制屏幕將有一些元素,例如 –
將顯示視頻媒體屏幕的視頻元素
開始按鈕將開始視頻錄制
停止按鈕將停止視頻錄制流。
對于音頻錄制,它將有兩個按鈕
開始按鈕將開始錄音
停止按鈕將停止音頻錄制流。
我們將添加 font Awesome CDN 以添加開始和停止按鈕圖標(biāo),并且為了使頁面更具吸引力,我們將在元素上添加 CSS 樣式。
HTML 代碼
示例
<!DOCTYPE html>
<html>
<head>
<title>Video & Audio Recorder</title>
<link rel="stylesheet" >
<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>
登錄后復(fù)制
當(dāng)您點擊“開始視頻”按鈕時,它將調(diào)用start_video_Recording()函數(shù),而“停止”按鈕將調(diào)用stop_Recording () 類似地,對于音頻,單擊開始按鈕將觸發(fā)函數(shù) start_audio_Recording() ,對于停止按鈕 stop_Recording() 函數(shù)將被調(diào)用。
start_video_Recording() 函數(shù)
讓我們定義一個函數(shù)來啟動視頻并錄制它。
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;
});
}
登錄后復(fù)制
當(dāng)按下開始按鈕時,它將調(diào)用上述函數(shù),這將觸發(fā) WebRTC 攝像頭和麥克風(fēng)方法來獲取錄制權(quán)限,并將啟用停止錄制按鈕并禁用開始錄制按鈕。
當(dāng)按下停止按鈕時,它將調(diào)用 stop() 函數(shù)并停止所有媒體流軌道。
然后為了記錄媒體流,我們將創(chuàng)建一個媒體記錄器實例并使媒體流以及媒體重新排序全局。然后停止視頻將停止媒體流,創(chuàng)建視頻元素將創(chuàng)建一個新的視頻元素并存儲錄制的媒體數(shù)據(jù)。
同樣,start_audio_Recording() 函數(shù)也與 start_video_Recording() 函數(shù)類似,但需要進行一些更改。
stop_Recording()函數(shù)
現(xiàn)在讓我們定義一個函數(shù)來停止錄制。
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;
}
登錄后復(fù)制
此函數(shù)將停止存儲在媒體流中的所有媒體軌道。
示例
讓我們將上述函數(shù)添加到 HTML 代碼中,以實現(xiàn)視頻和音頻錄制功能。
<!DOCTYPE html>
<html>
<head>
<title>Video & Audio Recorder</title>
<link rel="stylesheet" >
<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>
登錄后復(fù)制
從輸出中可以看出,當(dāng)單擊視頻開始按鈕時,它會調(diào)用 start_video_Recording() 函數(shù),并在該函數(shù)中調(diào)用 navigator.mediaDevices.getUserMedia() 方法,并打開一個權(quán)限菜單,用于查找視頻和麥克風(fēng)權(quán)限。它返回一個解析媒體流的承諾。在接收到音頻或視頻媒體流后,它會創(chuàng)建一個媒體記錄器的實例,并通過調(diào)用上述代碼中的函數(shù) medRec.start() 來開始記錄。
因此,您將了解使用 WebRTC 創(chuàng)建視頻和音頻錄制的完整過程。
以上就是如何使用 JavaScript MediaRecorder API 創(chuàng)建視頻和音頻錄制器?的詳細(xì)內(nèi)容,更多請關(guān)注www.92cms.cn其它相關(guān)文章!






