WebRTC API获取音视频设备数据

一. getUserMedia

        WebRTC 提供了 mediaDevices.getUserMeida API 获取系统音视频设备数据。

        var promise = navigator.mediaDevices.getUserMedia(constraints);

        调用该函数后会提示用户给予访问音视频设备的许可,调用成功后返回一个 Promise 对象,完成时会接收一个 MediaStream 对象。

        constraints 是一个 MediaStreamConstraints 对象,结构如下所示。

dictionary MediaStreamConstraints {
    (boolean or MediaTrackConstraints) video = false;
    (boolean or MediaTrackConstraints) audio = false;
}

        当调用 getUserMedia 时传入的 constraints 为 {audio: true, video: true} 表示想要获取音频和视频设备的数据,当然 video 和 audio 都可以指定更详细的参数。

二. 实例演示

1. 获取音频设备数据

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>WebRTC获取音频数据</title>
    </head>
    <body>
        <audio autoplay controls id="audio_player"></audio>
        <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
        <script src="./js/get_audio_stream.js"></script>
    </body>
</html>
'use strict'

var audioPlayer = document.querySelector("audio#audio_player");

function HandleError(err) {
    console.log(err.name + "," + err.message);
}

function GetAudioStream(mediaStream) {
    audioPlayer.srcObject = mediaStream;
}

if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
    console.log('getUserMedia is not supported!');
} else {
    var constraints = {
        audio : {
            echoCancellation : true,    // 回声消除
            noiseSuppression : true,    // 降噪
            autoGainControl  : true     // 自动增益
        }
    };
    navigator.mediaDevices.getUserMedia(constraints)
        .then(GetAudioStream)
        .catch(HandleError);
}

        对于音频选项可以通过 echoCancellation 设置是否启用回声消除,noiseSuppression 设置是否开启降噪,autoGainControl 设置是否开启自动增益。

         运行后效果如下所示,通过输入设备采集声音后可以从输出设备播放。

2. 同时获取音视频设备数据

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>WebRTC获取音视频数据</title>
    </head>
    <body>
        <video autoplay playsinline id="video_player"></video>
        <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
        <script src="./js/get_media_streams.js"></script>
    </body>
</html>
'use strict'

var videoPlayer = document.querySelector("video#video_player");

function HandleError(err) {
    console.log(err.name + "," + err.message);
}

function GetMediaStream(mediaStream) {
    videoPlayer.srcObject = mediaStream;
}

if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
    console.log('getUserMedia is not supported!');
} else {
    var constraints = {
        video : {
            frameRate   : { min : 5 },                // 最小帧率
            width       : { min : 640, ideal : 1080}, // 宽度   
            height      : { min : 360, ideal : 720},  // 高度  
            aspectRadio : 16/9                        // 宽高比
        },
        audio : {
            echoCancellation : true,
            noiseSuppression : true,
            autoGainControl  : true
        }
    };

    navigator.mediaDevices.getUserMedia(constraints)
        .then(GetMediaStream)
        .catch(HandleError);
}

        对于视频可以通过 frameRate 设置最小/理想帧率,通过 width 设置最小/理想宽度,通过 height 设置最小/理想高度,通过 aspectRadio 设置宽高比。

        运行后效果如下,可以看到视频输入设备采集的图像,也可以听到音频输入设备采集的声音。

3. 获取指定输入设备的音视频流

        获取指定输入设备的音视频数据,就是在 getUserMedia 的 constraints 加上 deviceId 的限制,实例代码如下。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>WebRTC获取音视频设备流</title>
    </head>
    <body>
        <div>
            <label>音频输入设备</label>
            <select id="audio_input"></select>
        </div>
        <div>
            <label>视频输入设备</label>
            <select id="video_input"></select>
        </div>
        <video autoplay playsinline id="video_player"></video>
        <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
        <script src="./js/get_device_media_stream.js"></script>
    </body>
</html>
'use strict'

var audioInput  = document.querySelector("select#audio_input");
var videoInput  = document.querySelector("select#video_input");
var videoPlayer = document.querySelector("video#video_player");

function HandleError(err) {
    console.log(err.name + "," + err.message);
}

function GetDevices(deviceInfos) {
    audioInput.innerHTML = "";
    videoInput.innerHTML = "";
    deviceInfos.forEach(function(deviceInfo) {
        console.log("kind : " + deviceInfo.kind +
                    ", label:" + deviceInfo.label +
                    ", groupId:" + deviceInfo.groupId +
                    ", deviceId:" + deviceInfo.deviceId); 
        var option = document.createElement("option");
        option.text = deviceInfo.label;
        option.value = deviceInfo.deviceId;
        if (deviceInfo.kind === "audioinput") {
            audioInput.appendChild(option);
        } else if(deviceInfo.kind === "videoinput") {
            videoInput.appendChild(option);
        } else {
            console.log("unknown device kind");
        }
    });
}

function GetMediaStream(mediaStream) {
    videoPlayer.srcObject = mediaStream;
    return navigator.mediaDevices.enumerateDevices();
}

function Start() {
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        console.log('getUserMedia is not supported!');
    } else {
        var videoDeviceId = videoInput.value;
        var audioDeviceId = audioInput.value;
        var constraints = {
            video : {
                frameRate   : { min : 20 },
                width       : { min : 640, ideal : 640},
                height      : { min : 360, ideal : 480},
                aspectRatio : 16/9,
                deviceId    : videoDeviceId ? videoDeviceId : undefined
            },
            audio : {
                echoCancellation : true,
                noiseSuppression : true,
                autoGainControl  : true,
                deviceId         : audioDeviceId
            }
        };
        navigator.mediaDevices.getUserMedia(constraints)
            .then(GetMediaStream)
            .then(GetDevices)
            .catch(HandleError);
    }
}

Start();

videoInput.onchange = Start;
audioInput.onchange = Start;

         运行后效果如下所示,可以看到指定输入设备采集的数据,并且点击输入设备的 select 框切换设备,可以看到指定设备采集的数据。

猜你喜欢

转载自blog.csdn.net/weixin_38102771/article/details/123613629