2

I think I'm over-complicating things for a beginner but all I wanted to do was add addEventListener at once to four of my buttons. Then pass on that event, to a new function which checks which button fired the event. After which, corresponding function is called for each button.

Thing goes good up until here. Everything works fine, I can even get console to log message from every function but, everything else but, audio doesn't pause. Audio plays fine but doesn't pause, I'm thinking global - local variable issue but upon checking in DevTools, console.log says same audio is being passed to my pause function but still doesn't pause it. Didn't want to take this last resort but been working on this since yesterday, any insight would be great.

var audioBar = document.getElementsByClassName("audioBar");
var playerBtn = document.getElementsByClassName("playerBtn");
var prev = document.getElementById('prev');
var play = document.getElementById('play');
var pause = document.getElementById('pause');
var pause = document.getElementById('stop');
var next = document.getElementById('next');
var seek = document.getElementById("seek");

var eListener;
for (var i = 0; i < playerBtn.length; i++) {
    playerBtn[i].addEventListener("click", whichButton, true);
    eListener = playerBtn[i];
}

function whichButton(eListener) {
    var whichID = eListener.target.parentElement.id;
    var whichClass = eListener.target.className;
    event.preventDefault();
    switch (whichID) {
        case "prev":
            // event.preventDefault();
            prevIt();
            break;
        case "play":
            // event.preventDefault();
            playIt();
            break;
        case "stop":
            // event.preventDefault();
            stopIt();
            break;
        case "next":
            // event.preventDefault();
            nextIt();
            break;
        default:
            event.preventDefault();
    }

    var passenger; //Declaring passenger on global scale within whichButton
    function playIt() {
        // var currentSong;
        function audio(src) { //constructor for audio for future efficiency
            var currentSong = new Audio(src);
            this.src = src;
            this.play = function () {
                currentSong.play();
            };
            this.pause = function () {
                currentSong.pause();
            };
            this.stop = function () {
                currentSong.pause();
                currentSong.currentTime = 0
            };
            // return currentSong;
        }

        passenger = new audio(songs[0].file); //The passenger that's been playing around.
        if (whichClass === "fa fa-play fa-2x") {
            event.target.className = "fa fa-pause fa-2x";
            // console.log(whichClass);
            console.log("playing it");
            passenger.play();
            console.log(passenger); //Checking which passenger is being played
        } else {
            event.target.className = "fa fa-play fa-2x";
            // console.log(whichClass);
            console.log("pausing it"); // << This works great!
            passenger.pause(); // << But this does not
        }
        // return passenger;
    }
    console.log(passenger); //Same passenger as the above one

    function stopIt() {
        passenger.stop(); //passing Same passenger to stop function but does not do it.
        passenger.pause();
        passenger.currentTime = 0;
        console.log("stopping it");

    }

    function nextIt() {
        console.log("next one");
    }
}
audioPlayerContainer {

    background: -webkit-linear-gradient(top, #494949 0%, #434242 31%, #393838 55%, #242323 83%, #1b1a1a 100%, #161515 100%, #0b0b0b 100%);

    /*background: -webkit-linear-gradient(top, #cc4b56 0%, #c01f2c 31%, #c01f2c 55%, #c01f2c 83%, #c01f2c 100%, #ac1b27 100%, #991823 100%);*/

    border: #c01f2c solid 4px;

    border-top: #fff solid 1.5px;

    width: 100%;

    height: 50px;

    position: fixed;

    bottom: 0;

    /*padding: 5px 50px 5px 0;*/

}

.relativeWrapper {

    position: relative;

    height: 100%;

    box-sizing: border-box;

}

.audioBar {

    display: inline-block;

    background: #c01f2c;

    width: 15%;

    height: 100%;

    font-size: 2rem;

    line-height: 1rem;

    text-align: center;

    box-sizing: border-box;

    float: left;

}

.audioBar h6 {

    top:50%;

    transform: translateY(-50%);

    position: relative;

    line-height: 1.1rem;

}

.fa-music {

    font-size: 2rem;

    float: left;

    margin: 0 0 0 15%;

}

.aPCController {

    display: inline;

    float: left;

    color: #f2f2f2;

    margin-left: 2%;

    width: 15%;

    height: 35px;

    /*padding-top: 0.25%;*/

    top: 50%;

    transform: translateY(-50%);

    position: relative;

    /*background: #f4c5c4;*/

}

.aPCController a {

    color:#fff;

}

.aPCController a~a {

    margin-left: 15px;

}

.seekWrapper {

    position: relative;

    float: left;

    background: #2f2f2f;

    height: 35px;

    top: 50%;

    transform: translateY(-50%);

}

.seek {

    width: 55%;

    /*display: inline-block;*/

}

.seekWrapper input {

    /*For div*/

    display: block;

    font-size: 0px;

    background: #c01f2c;

    /*width: 50%;*/

    height: 100%;

    /*For input*/

    -webkit-appearance: none;

    width: 100%;

    cursor: pointer;

}

.seekWrapper input::-webkit-slider-thumb {

    -webkit-appearance: none;

    border: 2px solid #000;

    /*border-radius: 25%;*/

    background: #fff;

    width: 15px;

    height: 35px;

    margin-top: -1px;

}

span #title {

    text-align: center;

    vertical-align: middle;

    color: #fff;

    /*display: inline;*/

}

.vol {

    width: 10%;

    margin-left: 1%;

}

canvas {

    top: 50%;

    -webkit-box-shadow: inset 0 0 10px #000000;

    box-shadow: inset 0 0 10px #000000;

}
<div class="audioPlayerContainer wrapper">
    <div class="relativeWrapper">
        <!--<div class="audioBar"></div>-->
        <div class="audioBar">
            <h6><i class="fa fa-music fa-2x"></i>audio </br> bar</h6>
        </div>
        <div class="aPCController"> <a class="playerBtn" id="prev" href="" title=""><i class="fa fa-step-backward fa-2x"></i></a>
 <a class="playerBtn" id="play" href="" title=""><i class="fa fa-play fa-2x"></i></a>
 <a class="playerBtn" id="stop" href="" title=""><i class="fa fa-stop fa-2x"></i></a>
 <a class="playerBtn" id="next" href="" title=""><i class="fa fa-step-forward fa-2x"></i></a>

        </div>
        <!--<div id="seekWrapper"><p id="seek"><span id="title">some random title</span></p></div>-->
        <div class="seekWrapper seek" id="seekWrapper">
            <input type="range" id="seek" value="0" max=""><span class="_label"><p>RadioHead - Creep</p></span>
        </div>
        <div class="seekWrapper vol" id="volWrapper">
            <input type="range" id="vol" value="0" max="10">
        </div>
        <!--<canvas id="previous" width="50px" height="50px" onmouseover=""></canvas>
            <canvas id="play" width="50px" height="50px" onmouseover=""></canvas>
            <canvas id="next" width="50px" height="50px" onmouseover=""></canvas>-->
    </div>
</div>

Let me know if any other details is needed. Thanks!

Edit: The only case where I got the passenger to stop or pause was when I passed the passenger parameter straight away to stopIt function like this, which further makes me believe this is the case of global/local variable dispute. But for a novice, I can't see anything. Researched a lot, tried a lot, still to no avail.

passenger = new audio(songs[0].file);                     //The passenger that's being playing around.
      if (whichClass === "fa fa-play fa-2x"){
            event.target.className = "fa fa-pause fa-2x";
            // console.log(whichClass);
            console.log("playing it");
            passenger.play();
            stopIt(passenger);    // <<<<<Only if I do this, it stops
          }
      else {
            event.target.className = "fa fa-play fa-2x";
            // console.log(whichClass);
            console.log("pausing it");       // << This works great!
            passenger.pause();              // << But this does not
          }
    // return passenger;
  }          

function stopIt(stopThis){
      stopThis.stop();                  
      stopThis.pause();
      stopThis.currentTime = 0;
      console.log("stopping it");

  }

This way it pauses/stops but it stops as soon as the passenger starts playing, without click on stop button, as the function is being called by playIt function not the click Event. So don't know what to do.

mido
  • 24,198
  • 15
  • 92
  • 117
  • 1
    If every cases calls the `preventDefault()`, call it outside the `switch`, `event` is undefined, you named it `eListener` – Kaiido Oct 05 '15 at 06:31
  • @Kaiido I'm not sure about calling it outside. I'll try it thanks. Did you mean you tried it at your end and got event => undefined? Should I post the whole thing? HTML and the whole JS? – Схирисх Шреста Oct 05 '15 at 06:37
  • call it just outside the `switch()` , but inside the `whichButton`. I didn't tried to run your code, but just reading was enough to find those first problems, there might be another one, that could be more easily detected with an actual working snippet yes. – Kaiido Oct 05 '15 at 06:39
  • Calling `preventDefault()` outside worked, thanks for that bit. Quick question, I wouldn't have any default case for it and as far as I know switch needs a default case? or I just throw a random error message? – Схирисх Шреста Oct 05 '15 at 06:40
  • http://stackoverflow.com/questions/4649423/should-switch-statements-always-contain-a-default-clause – Kaiido Oct 05 '15 at 06:45
  • Yeah thought so. I'll make yet another change on my workspace. But there you go, the whole code. And as edited note says, buttons won't be visible coz of font awesome. – Схирисх Шреста Oct 05 '15 at 06:49

4 Answers4

0

before playing any audio/video file you have to load it first. eg,

this.play = function(){
  currentSong.load();
  currentSong.play();
};

May this will solve your problem.

Shashank Dave
  • 145
  • 12
0

the main issue here is, whichButton is not the same object that is shared between the various play buttons as event listener, thus when you put the passenger outside, it would be truly global, also there were other little issues, fixed them in the demo:

fiddle demo

Community
  • 1
  • 1
mido
  • 24,198
  • 15
  • 92
  • 117
  • Thanks for the answer. I've looked at it and I've seen similar examples in tutorials. Adding EventListener directly to the whole container and loading the audio through HTML markups. I've tried relating it to mine, and what I can't figure out is if `whichButton` is not being shared then at least, the `else` statement should have worked as it is listening to the same id and variable. Also, I tried keeping `passenger` inside, outside, everywhere, you name it. I'll try to figure this out by next 12 hours, if not I'll go by the book. Don't try fancy until I'm better at this. – Схирисх Шреста Oct 05 '15 at 09:17
  • @СхирисхШреста you wann know why pause is not working? that was because the JS object held by `passenger` kept changing... – mido Oct 05 '15 at 09:37
0
function whichButton(eListener) {
    var whichID = eListener.target.parentElement.id;
    var whichClass = eListener.target.className;
    event.preventDefault();

event is undefined... This will cause javascript error.

Legionar
  • 7,472
  • 2
  • 41
  • 70
0

A little late on this, but I figured I need to write what I did with this. Like mido22 suggested, I was having troubles with my passenger, so had to change it all. I had to rewrite most of the things.

Anyways, it's pretty messy, not working on this project so didn't care for presentation. Finished this long time back but forgot to come back to stackoverflow. Came here today to seek an answer to different query.

If anyone's interested, please let me know how I can make this code better.

var audioBar = document.getElementsByClassName("audioBar"),
      playerBtn = document.getElementsByClassName("playerBtn"),
      prev = document.getElementById('prev'),
      play = document.getElementById('play'),
      pause = document.getElementById('pause'),
      pause = document.getElementById('stop'),
      next = document.getElementById('next'),
      seek = document.getElementById("seek"),
      vol = document.getElementById("vol"),
      songInfo = document.getElementById("songInfo").querySelectorAll("p"),

      eListener;
  for(var i=0; i<playerBtn.length; i++){ 
      playerBtn[i].addEventListener("click", whichButton, true);
      eListener = playerBtn[i];
  }

  var audio = new Audio(), 
      factor = (seek.clientWidth/audio.duration) * parseFloat(audio.currentTime) / (seek.clientWidth/100);
      audio.src = function (){songs[0].file};
      vol.value = 5;

  function progress(){
    seek.value = 0;
    seek.value = (seek.clientWidth/audio.duration) * parseFloat(audio.currentTime) / (seek.clientWidth/100);
    songInfo[0].textContent = songs[0].artist + " - " + songs[0].title;
    songInfo[1].textContent = String(audio.currentTime).toTime() + " | " + String(audio.duration).toTime();

    if(audio.ended || audio.paused) {play.childNodes[0].className = "fa fa-play fa-2x";}
  }

  function volChange(){ vol.value = event.target.value; audio.volume = vol.value/10; }

  function seekupdate(){ seek.value = event.target.value; audio.currentTime = seek.value/(seek.clientWidth/audio.duration) * (seek.clientWidth/100) }

  audio.addEventListener("timeupdate", progress);
  seek.addEventListener("input", seekupdate);
  vol.addEventListener("input", volChange);

  function  whichButton(eListener){ 
      var whichID = eListener.target.parentElement.id,
          whichClass = eListener.target.className;
          event.preventDefault();

      if(!(audio.paused) && whichID === "stop") {audio.pause(); audio.currentTime = 0;}

      if((audio.paused) && whichClass === "fa fa-play fa-2x") {audio.play(); event.target.className = "fa fa-pause fa-2x";}

      if(!(audio.paused) && whichClass === "fa fa-pause fa-2x") {audio.pause(); event.target.className = "fa fa-play fa-2x";}

  }