How do I use Javascript to Select Audio File from Button Value

雨燕双飞 提交于 2019-12-12 02:40:02

问题


So I have an array of buttons all with different values and I want them play the song with it's number value, when clicked. All of the files are numbered, i.e. 1.mp3, 2.mp3, 3.mp3, etc.

Is there a way of doing it without a lot of repeating Javascript code for each song.

Here is my HTML:

<audio id="player">
        <source id="sourceMp3" src="" type="audio/mp3">
        Your browser does not support the audio element.
</audio>

<button onclick="loadSong()" value="1">1</button>
<button onclick="loadSong()" value="2">2</button>
<button onclick="loadSong()" value="3">3</button>
<button onclick="loadSong()" value="4">4</button>
<button onclick="loadSong()" value="5">5</button>

Here is my JavaScript:

function loadSong(){

var player=document.getElementById('player');
var songNo = document.getElementByTagName('button').value;
var sourceMp3=document.getElementById('player');

sourceMp3.src='songs/' + songNo + '.mp3;

player.load();
player.play(); 

}

Any suggestions would be greatly appreciated.


回答1:


Your call in the JS portion should be:

var sourceMp3=document.getElementById('sourceMp3');

Then

sourceMp3.src='songs/' + songNo + 'mp3';

should work.

Notice, you should pick the 'src' of the <source>-tag, not the <audio>-tag

also, I would add a function-call with the buttons: - and then define your function like this: function loadSong(songNo)...

So, your code could look like this:

<audio id="player">
    <source id="sourceMp3" src="" type="audio/mp3">
    Your browser does not support the audio element.
</audio>

<button onclick="loadSong(1)">1</button>
<button onclick="loadSong(2)">2</button>
<button onclick="loadSong(3)">3</button>
<button onclick="loadSong(4)">4</button>
<button onclick="loadSong(5)">5</button>

And the JS:

function loadSong(songNo) {
var player=document.getElementById('player');
var sourceMp3=document.getElementById('sourceMp3');
sourceMp3.src='songs/' + songNo + '.mp3';

player.load();
player.play();



回答2:


var songNo = this.value not var songNo = document.getElementByTagName('button').value;

document.getElementByTagName('button') returns HTMLCollection and loadSong is the handler of the click event so you have access to 'this'



来源:https://stackoverflow.com/questions/33378148/how-do-i-use-javascript-to-select-audio-file-from-button-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!