2

Can you detect if volume can be set with javascript? Like for example to see if you are on ios browser (but not detecting ios just if volume can be set). I tried something like this but it always returns true.

If I am on ios I want to hide my volume button in the player. I know I can detect ios, but I wanted to go step further and possibly detect if volume can be changed.

var audio = document.createElement("audio");
    if(!audio) return false;
    audio.volume = 0;
    return audio.volume == 0 ? true : false;
Toniq
  • 3,484
  • 8
  • 38
  • 84

3 Answers3

1

Getting same issue on iOS Safari. I can suggest async variant with volumechange event listener.

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])
}
0

Only think I could think of would be to listen for the volumechange event (which has universal support), and then set the volume like you're doing (which according to MDN has unknown support in many browsers) and see if it fires?

Alex Wayne
  • 145,435
  • 42
  • 271
  • 302
0

I had the same issue and after a couple hours I resigned myself to detecting iOS altogether. 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. However, the fact that setting the volume happens synchronously but the event happens asynchronously made it tricky.

simlmx
  • 658
  • 8
  • 12
  • You are saying Alksey's solutiong doesn't work in some scenarios? What are they? Seems to be working for me, unless I am missing some edge cases? – Mark Fisher Jan 18 '21 at 13:12