Reputation: 13
I have a list of sounds on my serveur called:
sound1.mp3, sound2.mp3, sound3.mp3 ...
I also have a list of pictures called: image1.jpg, image2.jpg, image3.jpg ...
I would like to play the sound1.mp3 when clicking the image1.jpg, the sound2.mp3 when pressing the image2.jpg, etc.. etc..
I'm not very good at javascript and I struggle with the quotations "" and ''..
<script>
function playSound(){
for (i = 1; i < 4; i++) {
'<audio id="sound' + i +'" src="mywebsite/sound'+ i + '.mp3"></audio>'
'<img src="mywebsite/image' + i + '.jpg" onclick="document.getElementById("sound"\i"\").play()"/>';
}
}
playSound();
</script>
Thanks very much for any help... !!!
Upvotes: 1
Views: 1166
Reputation: 452
Refactor your line 5 as follows
'<img src="mywebsite/image' + i + '.jpg" onclick="document.getElementById("sound' + i + '").play()"/>'
Upvotes: 0
Reputation: 5788
Run below snippet and Check console html string is there as per you expected.
function playSound(){
var htmltoappend = "";
for (i = 1; i < 4; i++) {
htmltoappend += '<audio id="sound' + i +'" src="mywebsite/sound'+ i + '.mp3"></audio>'
htmltoappend += '<img src="mywebsite/image' + i + '.jpg" onclick="document.getElementById("sound'+i+'").play()"/>';
}
console.log(htmltoappend);
}
playSound();
Upvotes: 1
Reputation: 52270
You can start playback of a single file with something like this:
var audio = new Audio('audio_file.mp3');
audio.play();
If you want to play successive files, you will need to capture the ended
event, like this:
function playFirstTwoFiles() {
var audio = new Audio('audio_file.mp3');
audio.addEventListener("ended", playSecondFile, true);
audio.play();
}
function playSecondFile() {
var audio = new Audio('audio_file_2.mp3');
audio.play();
}
Upvotes: 2