Give this a try. Copy and paste the code to your favorite editor and remember to replace the audio source for your own audio with the correct path save the document and fire up your favorite browser to test. Remember to add the audio file that will play in your browser because certain browsers only support certain audio file types See here for more information about browser file types support. Later on I will also explain how we can add other file type extentions to this script so that you are not limited to just one file type.
audio = new Audio();
audio.src = “MyAudio.mp3”;
audio.loop = true;
Explanation of the above code:
We start this example by using a basic html5 empy document.
Between the two “body” starting and closing tags we add our script starting and closing tags. Between the script tags we put all the dynamics for the audio object.
To start with on our first line we set or add the ‘audio’ variable.
On the next line of code we add a stream audio source. (To test this document for yourself you would need to replace the” MyAudio.mp3″ for your own, making sure that you have the correct path to your audio file.
We then add another property of the audio object the “loop” which allows the audio to loop ‘true’ or ‘false’. Another words, to play again after the audio has finished ‘true’ or not play again after the audio has finished “false”
Our final line within this function is “audio.play” this will allow the audio to play in our document.
On the last line before the closing script tag, we add the eventlistener so that all assets are loaded only after all assets the have been loaded in to the document, it will make “initAudioPlayer function execute.
This basic script allows us to call the audio object and play the audio in our document. Which is great if you just want background music to play when the page is opened but of course the user can not stop the audio or even turn down to volume there are no controls etc. But with this basic setup we can add many different types of controls to our audio object which we will be discussing in our next article.
Here we have created a new audio object through the code. We assigned a new source file for it in this section we called it “My-audio” but you would need to apply your own audio source and the correct path. We then added the code to make the audio loop ‘true’ or ‘false’ the final line we instruct the audio to play.
Was this helpful?
Please support us by liking us on facebook at the top of the page. Contact me if you have any questions or suggestions about this topic.
Next: Part B: