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.

  1. Create a new stack and set the name to "HTML5PlaySound"
  2. Add a "Play" button
  3. 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

Copy the sound file you want to play into the standalone folder.

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>.

  <audio id="myAudio">
    <source src="piano-melody.wav" type="audio/wav">
  </audio>

For further information on this see this tutorial

https://www.w3schools.com/jsref/met_audio_play.asp

Run the app

To run the app open the HTML file in a browser and try the Play and Pause buttons.

0 Comments

Add your comment

E-Mail me when someone replies to this comment