Reputation: 374
So I am trying to make a radio station project just for fun. Where in the start it will play an audio file saying like: "Welcome to the beat at 97.5" or whatever and then it would choose a random song and after it ends it would play an audio file saying "that was the awesome beat. Moving on to the next!" and it would play a different random song
Exciting part! Code! I tried doing this:
var audio = new Audio("test.mp3");
audio.play();
It just wouldnt play anything? Whats the easiest and fastest way to play an audio with JavaScript? Please no HTML involved.
EDIT: Tried to use Howler.js but wouldnt do anything still? Here is the code:
//I moved it
var sound = new Howl({
urls: ['/audio/test.mp3']
}).play();
this is the directory: C:\Websites\infiniteradiostation\audio\test.mp3
Upvotes: 0
Views: 1941
Reputation: 1
The code you have written is correct, but the problem is that most browsers (including chrome, edge etc.) does not allow auto-play of sound unless the user has interacted with it. This has been done to enhance the user-experience. To verify that your code is running you can go to browser's console and run the code audio.play()
and the intended audio should play.
Upvotes: 0
Reputation: 6885
The code you have posted looks good, please check the javascript console that there are no errors and make sure that the path of the file is correct.
Other than that you also have multiple options that you can use to enhance the functionality.
SoundManager2 is an excellent library that provides tons of features(and backward compatibility too if you prefer).
The sample code will be something like this.
<script src="/path/to/soundmanager2.js"></script>
<script>
soundManager.setup({
url: '/path/to/swf-files/',
onready: function() {
var mySound = soundManager.createSound({
id: 'aSound',
url: '/path/to/an.mp3'
});
mySound.play();
}
});
</script>
Howler too an excellent library thats worth looking.Its example code will be some thing like this
var sound = new Howl({
urls: ['sound.mp3', 'sound.ogg', 'sound.wav'],
autoplay: true,
loop: true,
volume: 0.5,
onend: function() {
alert('Finished!');
}
});
Upvotes: 1
Reputation: 119
That code should work. Which browser are you using?
Alternative way with more options would be using this library http://goldfirestudios.com/blog/104/howler.js-Modern-Web-Audio-Javascript-Library
Upvotes: 0