0 votes
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
by (63.1k 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. 

by (160 points)

other way is to find the created audio element and call actions on it

 // this will find first audio element in html and pauses it
 $('audio')[0].pause();

or you can stop all the music present (credits) ..

$('audio').each(function(){
    this.pause(); // Stop playing
    this.currentTime = 0; // Reset time
});

 

...