使用JavaScript获取和设置音量

    技术2022-07-11  126

    The <audio> and <video> tags provide a wealth more functionality than most people know. For instance, did you know that you could detect supported video formats and audio formats using a few JavaScript tricks?  It got me to thinking about the possibilities of detecting system volume with JavaScript in the browser.

    <audio>和<video>标签提供了比大多数人所知道的功能更多的功能。 例如,您是否知道您可以使用一些JavaScript技巧来检测受支持的视频格式和音频格式 ? 我不得不考虑使用浏览器中JavaScript检测系统容量的可能性。

    I hate to be a buzzkill but unfortunately JavaScript doesn't provide direct access to the system volume but you can, using <audio> and/or <video> elements, programmatically set and get the volume level.

    我讨厌成为嗡嗡声的杀手,但不幸的是JavaScript无法提供对系统音量的直接访问,但是您可以使用<audio>和/或<video>元素以编程方式设置并获取音量。

    // Getting volume level const volume = document.querySelector("video").volume; // 1 // Setting volume level document.querySelector("video").volume = 0.5; // set volume to 50%

    You can also listen for volume changes with the "onvolumechange" event:

    您还可以使用“ onvolumechange”事件来监听音量变化:

    document.querySelector("video").addEventListener("onvolumechange", e => { // Change your custom control UI });

    It makes sense that you can't set system volume level from a random JavaScript snippet in a browser but I had a slight hope you could retrieve that level.  Setting volume with JavaScript for a given piece of media is relative to system volume level but hey -- at least we get to create custom controls for those elements with .volume settings!

    不能从浏览器中的随机JavaScript代码段设置系统音量级别是有道理的,但是我有一点希望您可以检索该级别。 使用JavaScript为给定的媒体设置音量是相对于系统音量级别的,但是-至少我们可以使用.volume设置为这些元素创建自定义控件!

    翻译自: https://davidwalsh.name/javascript-volume

    相关资源:js实现播放器,有进度条,能控制音量
    Processed: 0.015, SQL: 10