Playing different Audio in different Scenes using the same ID

###Using the techniques described here and here I will demonstrate how you can play different audio in different scenes using the same function and same ID’s for the audio.

###Step 1

Add a function on Scene load and place the following in it:

hypeDocument.getCurrentSceneElement = function(){
	var  hc = document.getElementById(hypeDocument.documentId());
	var  sa =   hc.getElementsByClassName("HYPE_scene");
		for (i = 0; i <    sa.length; i++) {
			if (  sa[i].style.display === "block") return sa[i];

###Step 2

Create an element (e.g Rectangle) and inside the innerHTML place this code:

<audio id="myAudio" src="${resourcesFolderName}/MY.mp3"></audio>

#####*The source in this example is pointing to the resources folder but could be any url that contains audio. Also, MY.mp3 is just an example. You would replace this with your own audio file name.

Place this element anywhere you like (I prefer off scene)

###Step 3

Create your button elements for play and pause. Give them a class name of “play” and “pause” respectively.

###Step 4

Click on the play button in the scene and go to the Actions inspector. Click the plus icon next to “On Mouse Click” and choose “Run Javascript…” -> “New Function…” and in the pop up screen enter:

var sceneElement = hypeDocument.getCurrentSceneElement();

var myAudio = sceneElement.querySelector('#myAudio');

if (element.classList.contains('play')) {;
} else if (element.classList.contains('pause')) {

Now, all being well you should have a play button and pause button and when clicked they play and pause your audio.

Now duplicate the scene and select the innerHTML of the element that contains your audio and change it to another audio src:

<audio id="myAudio" src="${resourcesFolderName}/MySecondAudio.mp3"></audio>

#####*again this doesn’t have to be from the resources folder

and now when you transition to this scene from scene 1 you should be able to play the different audios using the same function.

Just one thing. Your audio will keep playing when you transition to the other scene so you need to call this function before you transition:

var sceneElement = hypeDocument.getCurrentSceneElement();

var myAudio = sceneElement.querySelector('#myAudio');


###Now you can duplicate the scenes and just change the url to the audio (or keep it the same) and have a way to play different audio on different scenes using minimal Javascript. (1.4 MB)