如何从选择中单击选项时更改音频源?

时间:2017-05-17 01:30:24

标签: javascript events audio option

我有一个声音数组,我将其归因于空音频 看起来像这样:

                <audio id = "audio4" controls>

                    <source id = "audioSourceAside" type="audio/mpeg">  

                </audio> 

我为我想要使用的每个选项添加了一个“更改”事件监听器,但它不起作用,音频源保持灰色,即使我强制它通过chrome的控制台获取源,它也是灰色的。

1 个答案:

答案 0 :(得分:0)

使用附加到change元素的<select>事件。在change处理程序中,在.pause()节点上调用<audio>,将.src元素的<source>设置为.value元素的<select>,然后调用.load(),然后在.play()上致电AudioNode

&#13;
&#13;
var select = document.querySelector("select");
var audio = document.querySelector("audio");
var source = audio.querySelector("source");
select.onchange = function() {
  audio.pause();
  source.src = this.value;
  audio.load();
  audio.play();
}
&#13;
<select>
  <option>Select audio to play</option>
  <option value="https://ia600305.us.archive.org/30/items/return_201605/return.mp3">RETURN by smiling cynic </option>
  <option value="https://upload.wikimedia.org/wikipedia/commons/b/be/Hidden_Tribe_-_Didgeridoo_1_Live.ogg">Didgeridoo 1 Live by Hidden Tribe</option>
</select>
<br>
<audio id="audio4" controls>
<source id="audioSourceAside">
</audio>
&#13;
&#13;
&#13;