Reputation: 11
this is my code it creates a new howl called sound, which defines some variables, than it plays a random song from a list of songs than after it ends, it ends the sound, unloads it and plays a different song from the list after it unloads and stops
function PlaySong(Choice, Songs) {
var Choice = Math.floor(Math.random() * 16);
var sound = new Howl({
src: [Songs[Choice]],
html5: true,
onend: function () {
sound.stop();
sound.unload();
PlaySong(Choice, Songs)
}
});
sound.play();
}
Upvotes: 1
Views: 2408
Reputation: 952
This is how you could program it without Howler - just using the HTML5 audio tag. (I used Howler myself, but it's quite complex and seemed to have issues with not properly unloading played audio files. Then I switched to plain HTML5 audio, which solved my problems.)
<audio id="audio"></audio>
<input type="button" onclick="playNextSong()" value="Play" />
<script>
const songs = ['file1.mp3', 'file2.mp3', 'file3.mp3'];
const playNextSong = () => {
const audioTag = document.getElementById("audio");
audioTag.src = songs[Math.floor(Math.random() * songs.length)];
audioTag.play();
audioTag.onended = playNextSong;
}
</script>
Please note, that the initial play has to be triggered by a user action (e.g. button click). Browser won't let you play anything until one such event occurred (to prevent noisy ads, I guess). The typical solution would be having an "enter" button at the beginning of your webapp, which plays 1 second of a silent mp3 just to enable sound playback.
I don't know Blazor webassembly, so you will have to see how to translate that.
Upvotes: 1