使用 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();

现场演示