0 votes
asked by (180 points)

Hello!

I am using a click-to-play code that plays my background audio so it works in web browser. This music works as background music and plays until it times out. Though, I would like a code that will allow me to click a "game over" hypertext that stops the music. 

My current javascript is: 

$(document).on('click', '.audio', function () {
    new Audio('https://...com/audio.mp3').play();
});

Inside the passage, I am using: 

[[<span class='audio'>PRESS START ▼</span>|1]]

I know there's probably an easy solution...just don't know what it is yet. Thanks for all your help!!

1 Answer

0 votes
answered by (57.2k points)

You'll need to cache a reference to that Audio instance so you can do more stuff to it. For example: 

var song = new Audio(...);

$(document).on('click', '.audio tw-link', function () {
    song.play();
});

$(document).on('click', '.audio-stop tw-link', function () {
    song.pause();
    song.currentTime = 0;
});

You'll notice that I changed the selectors to '.class tw-link'. So you'd move your spans out of the link markup to use this, which is safer than putting them inside the markup: 

<span class='audio'>[[link]]</span>

Also, I have heard that creating an actual <audio> element (with jQuery, probably) rather than using the Audio constructor is better, but someone more knowledgeable than me would probably know more about that. 

Welcome to Twine Q&A, where you can ask questions and receive answers from other members of the community.

You can also find hints and information on Twine on the official wiki and the old forums archive.

See a spam question? Flag it instead of downvoting. A question flagged enough times will automatically be hidden while moderators review it.
...