Audio track handler not working

I’m trying to check if a song is playing so if it is, it won’t start over, but can’t get anything to work. I tried a widget that should if the song is playing, but doesn’t recognize a match.

Here is my JS:

window.isPlaying = function (BGM) {
	var track = SimpleAudio.tracks.get(BGM);
	if (track != null) {
		if (!track.audio.paused && track.audio.duration) {
			return true;
		}
	}
	return false;
};

and here’s my StoryInit:

<<widget "ChangeMusic">>
    <<if !isPlaying($args[0])>>
        <<masteraudio stop>>
        <<audio $args[0] play loop volume 0.25>>
	<<else>><<audio $args[0] play loop>>
	<<endif>>
<</widget>>

The widget will play the given song when used, but won’t prevent it from starting over when I return to the passage. Any help or direction is much appreciated.

If you’re using SugarCube v2.28.0 or later, then your “isPlaying” function should be more like this:

// Check to see if trackID is the currently playing track
window.isPlaying = function (trackID) {
	var track = SimpleAudio.tracks.get(trackID);
	return track !== null && track.isPlaying();
};

Also, you shouldn’t put widgets in any special passages, like StoryInit. See the warnings in the <<widget>> macro documentation.

What you’re using looks like an earlier version of some code I wrote, which had to be revised when SugarCube updated its audio code. If you want the current version of my code, you can find my music sample code here. (Click “Jump to Start” in the UI bar to see other sample code there.)

Hope that helps! :slight_smile:

1 Like

I recognize your from that thread, thanks so much for helping me out! I hadn’t looked at your site but have now implemented all your code and it’s working great. :smile: