How do I play sound files in HTML5?
In the lesson we will see how to play a sound file in HTML5. To achieve this we will use JavaScript.
Create the stack
Begin by creating the UI for the stack.
- Create a new stack and set the name to "HTML5PlaySound"
- Add a "Play" button
- Add a "Pause" button
Set the script of the "Play" button
Set the script of the "Play" button to
on mouseUp
playSound
end mouseUp
Add the playSound
command to the Card Script
command playSound
local tScript
if the platform is "html5" then
put "document.getElementById('myAudio').play()" into tScript
do tScript as "JavaScript"
disable button "play"
enable button "pause"
end if
end playSound
- Check the platform is "html5"
- Set up the JavaScript that will play the sound file
- Execute the JavaScript
- Update the state of the buttons
Set the script of the "Pause" button
Set the script of the "Pause" button to
on mouseUp
pauseSound
end mouseUp
Add the pauseSound
command to the Card Script
command pauseSound
local tScript
if the platform is "html5" then
put "document.getElementById('myAudio').pause()" into tScript
do tScript as "JavaScript"
enable button "play"
disable button "pause"
end if
end pauseSound
- Check the platform is "html5"
- Set up the JavaScript that will pause the sound file
- Execute the JavaScript
- Update the state of the buttons
Save the standalone
Build the stack as an HTML5 standalone.
This will create a folder containing 4 files
- HTML file
- standalone.zip
- .mem file
- .js file
Copy the sound file into the standalone folder
Open the folder that was created when you built the standalone and copy the sound file you want to play into the standalone folder.
You can put the sound file at the top level or in a subfolder. You will need to know the path to it for the next step.
Edit the HTML file
In order for the JavaScript to locate the sound file we need to add an audio tag to the HTML file.
Open the HTML file in an editor and add an audiotag to the <body>
. The src attribute of the source element is the path to the sound file within the folder.
<audio id="myAudio">
<source src="piano-melody.wav" type="audio/wav">
</audio>
For further information on this see this tutorial
Run the app
To run the app upload the files to your server or test using localhost.
John Burnett
I am not sure what you mean by "Copy the sound file you want to play into the standalone folder." Does it go anywhere in the folder? subfolder?
Elanor Buchanan
Hi John
I have updated the lesson to hopefully make this a bit clearer. Once you have built the standalone open the folder that was created and copy the sound file into it. It can be at the top level or you can create a sub folder, you just need to know where it is so you can add the audio element to the HTML file and set the src attribute to the path to the sound file.
I hope that helps.
Elanor