Jackk1ng
Jackk1ng

Reputation: 11

Pause music with fade in/out when paused?

I got a music script but when I hit space aka pause button I want it to pause the music which it already does but I want it to do it with a fade in/out like spotify

Here's my code that I've got so far:

var play = true;

var myAudio = document.getElementById("music");

function onKeyDown(event) {
        switch (event.keyCode) {
            case 32: //SpaceBar                    
                if (play) {
                    myAudio.pause();
                    play = false;
                } else {
                    myAudio.play();
                    play = true;
                }

                break;
        }
  return false;
}

window.addEventListener("keydown", onKeyDown, false);

Upvotes: 1

Views: 1030

Answers (1)

Dustin Stiles
Dustin Stiles

Reputation: 1424

I don't think this is possible with the native API. However, you definitely could create a helper function that can do this. You have access to the volume controls, so you could do something like this:

function fadeOut(song) {
  if (song.volume === 0) {
    play = false;
    // Pause the song so it doesn't keep playing in the background
    song.pause();
    return;
  }
  // Set your fadeout interval here
  song.volume -= someInterval;
  // Return this function after some interval, and pass it the same song
  return setTimeout(fadeOut, 100, song);
  // Change the timeout interval for faster / slower fades
  // Reverse this for a fade in effect
}

It is worth nothing that when you decrease the volume, this is the amount the volume goes down each time this function is called. The setTimeout interval is how OFTEN we call this function. So the faster the timeout and smaller volume changes are, the more 'smooth' the fadeout will sound. Just be careful not to get those two intervals mixed up. They both do different things.

EDIT: You may want to keep track of what the volume was when you started the fadeOut, that way, you can go back to it on the fadeIn. Otherwise you will be going from silence to full volume each time, which isn't very flexible or user friendly.

Upvotes: 3

Related Questions