效果

前端基础(三十六):读取本地音视频设备并进行播放-LMLPHP

navigator.mediaDevices.enumerateDevices

navigator.mediaDevices.getUserMedia

源码

<div id="app">
    <select id="audio-select">
        <option value="">请选择</option>
    </select>
    <select id="video-select">
        <option value="">请选择</option>
    </select>
    <video id="video" autoplay controls></video>
</div>

<script>
    window.onload = function () {
        const audioSelect = document.getElementById('audio-select');
        const videoSelect = document.getElementById('video-select');
        const video = document.getElementById('video');

        // 获取全部设备
        navigator.mediaDevices.enumerateDevices()
            .then(devices => {
                devices.forEach(device => {
                    let option = document.createElement('option');
                    option.value = JSON.stringify(device);
                    option.innerText = device.label;
                    switch (device.kind) {
                        case 'audioinput':
                        case 'audiooutput':
                            audioSelect.appendChild(option);
                            break;
                        case 'videoinput':
                            videoSelect.appendChild(option);
                            break;
                    }
                });
            })

        function videoChange(device) {
            if (!device) return;
            // 播放音视频
            navigator.mediaDevices.getUserMedia({ audio: audioSelect.value ? JSON.parse(audioSelect.value) : false, video: device })
                .then(stream => {
                    video.srcObject = stream;
                })
        }

        videoSelect.onchange = function (e) { videoChange(JSON.parse(e.target.value)) }
    }
</script>
07-10 07:21