Tfarcraw IIV
Tfarcraw IIV

Reputation: 129

Music controls with HTML and JavaScript

I have (many) images on my web page, and each plays a song when clicked. Later, I plan to play a random song with each image click, as each picture is an album cover. The code for each image looks a bit like this:

<a onclick="PlaySoundM4A('money');">
    <img class="mySlidesTwo fading" src="dark2.jpeg" style="height:21vh;width:21vh;max-width: 200px;max-height: 200px;">
</a>

And here is my JS function:

function PlaySoundM4A(fileName) {

    var mFour = new Audio(fileName + ".m4a");
    mFour.play();
}

I'd like to know how to have a menu (or at least a few buttons) that allow a user to pause, mute, or end the track. The issue is that the song is a variable set within this function. How do I reference it in another function (like a stop function)?

Upvotes: 0

Views: 170

Answers (3)

Wale A.
Wale A.

Reputation: 41

What if you make it a global variable

var mFour;
function PlaySoundM4A(fileName) {
    mFour = new Audio(fileName + ".m4a");
    mFour.play();
}

function StopSound(){
    mFour.stop();
}

Upvotes: 1

Mathew Berg
Mathew Berg

Reputation: 28750

The simplest way would be to create a variable outside your function (maybe on the global scope) that would store the song:

var myFour;

function PlaySoundM4A(fileName) {

    mFour = new Audio(fileName + ".m4a");
    mFour.play();
}

function stopFunction(){
    if(!myFour){ return; }

    //do the stop thing
}

Upvotes: 0

user9107868
user9107868

Reputation:

use the audio tag. See https://www.w3schools.com/html/html5_audio.asp for more information. Your script only has to set the display of the audio tag to show. The user can then control it by themselves, and you can similate this input to stop and start the audio.

Upvotes: 0

Related Questions