Add Sound Effects on Answer Clicks
Last updated
Last updated
Let's add some simple sound effects to your trivia game when a player answers a question.
1 - Find sound effects you would like to use or make your own. Files of type .mp3 are a good choice for web apps. You can download the two sounds below as a starting point.
2 - Create a folder named sounds
and place your sound files in it. Pay close attention to your files and folder structure for you app. Below is an example of what yours should look like.
index.html
style.css
code.js
sounds
sound_correct.mp3
sound_incorrect.mp3
3 - Declare variables for your sounds at the very top of your code.js file. They should be above the setup()
function. These lines create variables that will represent your sound files so that you can play them at a later point in your code. Also, since we are placing them at the top of your code and not inside any function, they are called global variables. This means we can access these variables inside any other function, which we will do next.
4 - Place the code shown below inside your onClickedAnswer( )
function to play the sounds at the appropriate time. Notice how we are combining the text and sound feedback in our if/else statements inside the code brackets { }
. Your text feedback will likely be different. So adjust as needed.
That's it. Your game should now play your sound effects when a player answers a question.
If you are using a longer sound file, like a song, you will want to know about the following two features.
pause( ) - This method will pause your sound. For example, soundCorrect.pause( );
currentTime - This property can be used to reset the sound to the beginning. For example, soundCorrect.currentTime = 0;