Turn off Background Sound in Harlowe 3.2.3

If you are requesting technical assistance with Twine, please specify:
Twine Version: 2, online
Story Format: Harlowe 3.2.3

I’m teaching some high school students how to use Twine to create interactive fiction. (I’m learning as I go too).
We’re basically using it as an introduction to coding.
I have a student that wants some background sound playing continuously throughout the story.
I found this code.

var audio= document.createElement('audio');
audio.loop = true;

When inserted into the JS page, seems to work great!
The question our student has, is it possible to stop playing the sound on specific pages… maybe using tags?

If you intend to include audio within a Harlowe project then I strongly suggest you install and using the Harlowe Audio Library, instead of crafting your own JavaScript based solution.

But to answer your question…

The HTML <audio> element doesn’t have a stop() function, so you need to use the pause() function combined with its currentTime attribute to simulate “stop”.

audio.currentTime = 0;

However in your use-case that will be difficult because the audio variable created by your sample code is not accessible once the contents of the Story JavaScript area has finished being processed.

To overcome this scope issue you will need to define the audio variable in a way that makes it more “global” in nature, and one method you can use to do this is to create your own Namespace (on the special global window variable) and then define the variable on that instead.

note: for consistency sake, the Twine Cookbook suggests using a name of setup.

/* Define your namespace. */
window.setup = window.setup || {};

setup.audio = document.createElement('audio');
setup.audio.src = 'music.mp3';
setup.audio.loop = true;

You should then be able to reference that setup.audio variable later in project by using a <script> element within the contents of a Passage.

	setup.audio.currentTime = 0;

warning: Calling the play() function from the Story JavaScript area of your project will likely cause an error, this is due to the fact that the security systems of most modern web-browsers (especially those used on mobile devices) don’t allow audio to play until the end-user has interacted with the page.

For this reason that play() function call should be removed from the Story JavaScript area and places in the ‘second’ (or later) Passage of your project.