获取设备

enumerateDevices(),方法可以获取的当前设备,所有可用设备。

代码

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport"
  6. content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  7. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  8. <title>Document</title>
  9. </head>
  10. <body>
  11. <video id="video" controls autoplay></video>
  12. </body>
  13. </html>
  14. <script>
  15. // 获取所有可用设备
  16. function updateDeviceList(){
  17. window.navigator.mediaDevices.enumerateDevices()
  18. .then(enumerateDevices => {
  19. enumerateDevices.forEach(e =>{
  20. console.log(`${e.deviceId} ${ e.kind} ${e.label} ${e.groupId}`)
  21. })
  22. })
  23. .catch(err =>{
  24. console.log(err.name + '' + err.message)
  25. })
  26. }
  27. // addEventListener 监听变化
  28. navigator.mediaDevices.addEventListener("devicechange", e =>{
  29. console.log('devicechange 监听设备运行时候热拔插',)
  30. updateDeviceList();
  31. })
  32. // 事件具柄监听变化
  33. navigator.mediaDevices.ondevicechange = (event)=> {
  34. console.log('ondevicechange句柄 监控设备运行时候热拔插')
  35. updateDeviceList()
  36. }
  37. </script>