javascript 检测 麦克风状态


< html lang="zh">
< head >
    < meta charset="UTF-8">
    < meta name="viewport" content="width=device-width, initial-scale=1.0">
    < title >麦克风监听示例
    < style >
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        #deviceList {
            margin-top: 20px;
        }
    

< body >
    < h1 >麦克风设备监听
    < button id="checkDevices">检查麦克风设备
    < div id="deviceList">

    < script >
        // 检查浏览器是否支持媒体设备
        if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
            const deviceListDiv = document.getElementById('deviceList');

            // 定义一个函数来获取并显示设备
            function getAudioInputDevices() {
                navigator.mediaDevices.enumerateDevices().then(devices => {
                    const audioInputs = devices.filter(device => device.kind === 'audioinput');
                    deviceListDiv.innerHTML = '< h2 >当前可用的麦克风设备:';
                    for(let device of audioInputs) {
                        const deviceItem = document.createElement('div');
                        deviceItem.textContent = `${device.label} (ID: ${device.deviceId})`;
                        deviceListDiv.appendChild(deviceItem);
                    }
                    if(audioInputs.length==0){
                        alert('没有可用的设备')
                    }else{
                        alert('检测麦克风接入')
                    }
                });
            }

            // 初始获取设备
            getAudioInputDevices();

            // 监听设备变化
            navigator.mediaDevices.ondevicechange = () => {
                console.log('设备发生变化');
                getAudioInputDevices();
            };

            // 添加按钮点击事件
            document.getElementById('checkDevices').addEventListener('click', getAudioInputDevices);
        } else {
            console.log('该浏览器不支持媒体设备API');
            document.getElementById('deviceList').textContent = '该浏览器不支持媒体设备API';
        }
    

  

posted @ 2024-08-30 18:34  一样菜  阅读(145)  评论(0编辑  收藏  举报