使用 getUserMedia() API Hello WebRTC 訪問你的音訊和視訊
navigator.mediaDevices
是目前適用於 Chrome 和 FF 的常用方法,用於獲取使用者媒體。
一個承諾的回撥,它會在成功時返回本地流
navigator.mediaDevices.getUserMedia({ audio: true, video: true })
.then(stream => {
// attach this stream to window object so you can reuse it later
window.localStream = stream;
// Your code to use the stream
})
.catch((err) =>{
console.log(err);
});
你可以將音訊和視訊約束傳遞給 getUserMedia,以控制捕獲設定,如解析度,幀速率,裝置首選項等。
將流附加到視訊元素
// Set the video element to autoplay to ensure the video appears live
videoElement.autoplay = true;
// Mute the local video so the audio output doesn't feedback into the input
videoElement.muted = true;
// attach the stream to the video element
停止視訊和音訊
localStream.getTracks().forEach((track) => {
track.stop();
});
只停止音訊
localStream.getAudioTracks()[0].stop();
只停止視訊
localStream.getVideoTracks()[0].stop();