Red Pill Reality
Red Pill Reality

Reputation: 35

Javascript audio does not stop and play multiple tracks simultaniously

Javascript audio does not stop and play multiple tracks simultaniously.

I'm trying to shuffle randomly number of MP3/WAV tracks and it working nicely up until the point it suppose to stop the last track so there is a live merge between the previous tracks and it obviously sounds like a mess.

I bet it's a tiny tweak to solve that issue but... :)

anyways Here is my code :

<!DOCTYPE html>
<html>
<head>
    <meta charset=utf-8>
    <title>&nbsp;</title>
</head>
<body>

Thanks in advance for your kind help :D

var t=setInterval(function(){myTimer()},3000);

var files=
[
    'Hezi-Gangina#1.mp3',
    'Hezi-Gangina#2.mp3',
    'Hezi-Gangina#3.mp3',
    'Hezi-Gangina#4.mp3'
];

function myTimer()
{

    if(audio)
    {
        audio.pause();
        audio.currentTime=0;
        delete audio;
    }

    var i=Math.floor(Math.random()*files.length);
    var url=files[i];

    var audio=new Audio(url);

    audio.play();

    document.title=url.replace(/\.[^/.]+$/,'');

}

</script>

</body>
</html>

Upvotes: 1

Views: 112

Answers (1)

obscure
obscure

Reputation: 12891

The problem is the interval's callback function myTimer().

Let's have a look:

if(audio)
{
    audio.pause();
    audio.currentTime=0;
    delete audio;
}

Above, you're checking for the existence of the variable audio but this condition won't ever be true. Why? It's defined after this check and it's defined in the local scope of the callback function:

var audio=new Audio(url);
audio.play();

So the local variable will be re-defined on each call to myTimer and just 'lives' inside this function.

To fix this, you need to make audio a global variable and modify the if check to like this:

if(audio != null)

this will make sure it won't try to stop the audio the first time.

Here's your modified code:

var audio=null;
var t=setInterval(function(){myTimer()},3000);
var files=
[
    'Hezi-Gangina#1.mp3',
    'Hezi-Gangina#2.mp3',
    'Hezi-Gangina#3.mp3',
    'Hezi-Gangina#4.mp3'
];

function myTimer()
{
    if(audio != null)
    {
        audio.pause();
        audio.currentTime=0;
        delete audio;
    }

    var i=Math.floor(Math.random()*files.length);
    var url=files[i];

    audio=new Audio(url);
    audio.play();
}

Upvotes: 1

Related Questions