Toggle play/pause of audio element


(Barry) #1

I’ve created a global audio element and set the source. I want to use one button to trigger the play/pause functionality (I’d rather not use the timeline for this).

In HeadHTML I’ve got this:

// Add audio
window.audioConv = document.createElement('audio');

Here’s my code for the button toggle:

//find out what scene we are on
var sceneNum = (hypeDocument.currentSceneName()).slice(6);

// Assign the right audio to the scene
audioConv.setAttribute('src', '${resourcesFolderName}/audio' + sceneNum + '.mp3');
  
//function to toggle play and and pause functionality on button
var buttonText = $(element).html();

if (buttonText == 'Play') {
 	$(element).html('Pause');
	audioConv.play();
	
}  else {

 $(element).html('Play');
 audioConv.pause();

};

The problem I have is that instead of playing from the currentTime of the audio, it plays from the start every time. If I log currentTime I find that, indeed, it is 0 and always 0.

How can I fix this?


(Mark Hunte) #2

I am assuming that this is because you are assigning the audio each time which will reset it to 0.

You can probably get around this by having a global var hold the current time for each audio at time of pause.


#3

I would separate the function into 2

1 on sceneload to load the audio and the other on click of the “button” to toggle play / pause

Also the reason it’s happening is what @MarkHunte said


(Barry) #4

Gents, thanks very much.

The problem was as you suggested - always resetting to 0. And loading audio on sceneload worked a treat.