Stumpp
Stumpp

Reputation: 289

HTML/js select audio output device in browser

I have a created a simple soundboard in HTML which includes simple lines like this:

<body>
    <audio id="sound1" src="mysound.wav"></audio>
    <button class="button" onclick="document.getElementById('sound1').play()">My sound</button>
</body>

Is there any way the user can select which audio output device the sound will be played through, with a dropdown menu or similar?

Upvotes: 1

Views: 4846

Answers (2)

Roman Azarov
Roman Azarov

Reputation: 121

Now it is possible.

First you can gather possible audiooutput devices by running navigator.mediaDevices.enumerateDevices() and filtering found devices by property 'kind' equal to 'audiooutput'.

Then you should use setSinkId() method of DOM's audio/video element. Looks like you have to run setSingId(someSelectedDeviceId) for each video/audio element on your HTML-page

This is quite new feature that still not supported by Safari. But Chrome and partially FireFox already have this support https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/setSinkId

Upvotes: 3

P.S.
P.S.

Reputation: 16384

Here is the example how to change audio.src via select:

function play() {
  document.getElementById('sound1').play()
  console.log(document.getElementById('sound1').getAttribute('src') + " starts playing")
}

function changeSound() {
  document.getElementById('sound1').src = document.getElementById('select').value
  console.log("selected sound: " + document.getElementById('sound1').src)
}
<audio id="sound1" src="mysound1.wav"></audio>
<select id="select" onchange="changeSound()">
  <option value="mysound1.wav">mysound1.wav</option>
  <option value="mysound2.wav">mysound2.wav</option>
  <option value="mysound3.wav">mysound3.wav</option>
</select>
<button class="button" onclick="play()">My sound</button>

Upvotes: -1

Related Questions