简体   繁体   English

Javascript检测是否可以设置音量

[英]Javascript detect if volume can be set

Can you detect if volume can be set with javascript?你能检测到是否可以用 javascript 设置音量吗? Like for example to see if you are on ios browser (but not detecting ios just if volume can be set).例如,看看您是否在 ios 浏览器上(但如果可以设置音量,则不检测 ios)。 I tried something like this but it always returns true.我尝试过这样的事情,但它总是返回 true。

If I am on ios I want to hide my volume button in the player.如果我在 ios 上,我想隐藏播放器中的音量按钮。 I know I can detect ios, but I wanted to go step further and possibly detect if volume can be changed.我知道我可以检测 ios,但我想更进一步,并可能检测是否可以更改音量。

var audio = document.createElement("audio");
    if(!audio) return false;
    audio.volume = 0;
    return audio.volume == 0 ? true : false;

Getting same issue on iOS Safari.在 iOS Safari 上遇到同样的问题。 I can suggest async variant with volumechange event listener.我可以建议使用volumechange事件侦听器的异步变体。

function testMediaElementVolumeSetterAsync () {
  const timeoutPromise = new Promise(resolve => setTimeout(resolve, 1e3, false))
  const promise = new Promise((resolve) => {
    let video = document.createElement('video')
    const handler = () => {
      video.removeEventListener('volumechange', handler)
      video = null

      resolve(true)
    }

    video.addEventListener('volumechange', handler)

    video.volume = 0.5
  })

  return Promise.race([promise, timeoutPromise])
}

我只能想到的是监听volumechange事件(它具有普遍支持),然后像你正在做的那样设置音量(根据MDN在许多浏览器中都有未知的支持),看看它是否会触发?

I had the same issue and after a couple hours I resigned myself to detecting iOS altogether.我遇到了同样的问题,几个小时后,我让自己完全检测 iOS I resisted but now the code actually feels cleaner.我拒绝了,但现在代码实际上感觉更干净了。

I tried Alex's idea which almost worked as the event is not triggered on iOS but is on other platforms.我尝试了Alex 的想法,该想法几乎奏效,因为该事件不是在 iOS 上触发的,而是在其他平台上触发的。 However, the fact that setting the volume happens synchronously but the event happens asynchronously made it tricky.然而,设置音量同步发生但事件异步发生的事实使它变得棘手。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM