Button of Volume control

Hi Friends, please, I need some help. I use a javascript player, the script works fine, but unfortunately does not have the volume control button function. How do I include the volume function in the code ?

  • and - volume button.
/*global $, document, alert*/

(function () {

  // Track multiple players on the page
  var bbplayers = [];


  // Stop all other bbplayers on page when starting another
  function stopAllBBPlayers() {
    var i = 0;
    for (i = 0; i < bbplayers.length; i++) {
      bbplayers[i].bbaudio.pause();
      bbplayers[i].updateDisplay();
    }
  }

  // Pad a number with leading zeros
  function zeroPad(number, places) {
    var zeros = places - number.toString().length + 1;
    return new Array(+(zeros > 0 && zeros)).join("0") + number;
  }


  // Convert seconds to mm:ss format
  function toTimeString(seconds) {
    if (isNaN(seconds)) {
      return "--:--";
    }
    var minutes = Math.floor(seconds / 60);
    seconds = seconds - minutes * 60;
    return zeroPad(minutes, 2) + ":" + zeroPad(seconds, 2);
  }


  // Parse out file name from path, unescape
  function parseTitle(path) {
    path = decodeURI(path);
    return path.split('/').pop().split('.').shift();
  }

  // Object to represent bbplayer
  var BBPlayer = function (elem) {
    this.bbplayer  = elem;
    this.bbaudio   = elem.getElementsByTagName("audio").item(0);
    this.bbdebug   = elem.getElementsByClassName("bb-debug").item(0);
    this.bbaudio.setAttribute("preload", "auto");
    this.state     = this.bbaudio.autoplay ? "playing" : "paused";
    this.repeat    = this.bbaudio.loop ? true : false;
    this.bbaudio.removeAttribute('loop'); // hijack the loop directive
    this.trackList = [];
    this.init();
  }


  // Debug logger
  BBPlayer.prototype.log = function (msg) {
    if (this.bbdebug) {
      this.bbdebug.appendChild(document.createTextNode(msg));
      this.bbdebug.appendChild(document.createElement('br'));
      this.bbdebug.scrollTop = (this.bbdebug.scrollHeight - this.bbdebug.clientHeight);
    }
  };


  // say if audio element can play file type
  BBPlayer.prototype.canPlay = function (extension) {
    if ((/mp3/i).test(extension) && this.bbaudio.canPlayType('audio/mp3')) {
      return true;
    }
    if ((/ogg/i).test(extension) && this.bbaudio.canPlayType('audio/ogg')) {
      return true;
    }
    return false;
  };


  // Set up multiple sources as track list,
  // Remove duplicate and unplayable sources
  BBPlayer.prototype.loadSources = function () {
    var self = this;
    var unused = [];
    self.log('func: loadSources');
    var sources = self.bbaudio.getElementsByTagName("source");
    [].forEach.call(
      self.bbaudio.getElementsByTagName("source"),
      function (elem) {
        var fileName  = elem.getAttribute('src').split('/').pop();
        var extension = fileName.split('.').pop();
        var trackName = fileName.split('.').shift();
        var playable  = self.canPlay(extension);
        if (self.trackList.indexOf(trackName) === -1 && playable === true) {
          self.trackList.push(trackName);
        } else {
          unused.push(elem);
        }
      }
    );
    [].forEach.call(
      unused,
      function (elem) {
        elem.parentNode.removeChild(elem);
      }
    );
  };


  // Update display
  BBPlayer.prototype.updateDisplay = function () {
    var audioElem = this.bbaudio;
    var duration  = toTimeString(Math.ceil(audioElem.duration));
    var elapsed   = toTimeString(Math.ceil(audioElem.currentTime));
    var title     = parseTitle(audioElem.currentSrc);
    this.bbplayer.getElementsByClassName('bb-trackTime').item(0).innerHTML = elapsed;
    var playButton = this.bbplayer.getElementsByClassName("bb-play").item(0);
    if (this.bbaudio.paused) {
      playButton.classList.remove("bb-playing");
      playButton.classList.add("bb-paused");
    } else {
      playButton.classList.remove("bb-paused");
      playButton.classList.add("bb-playing");
    }
  };


  // Set current source for audio to given track number
  BBPlayer.prototype.loadTrack = function (trackNumber) {
    var source = this.bbaudio.getElementsByTagName("source").item(trackNumber).getAttribute('src');
    this.bbaudio.src = source;
    // don't autoplay if bbplayer state is paused
    if (this.state === 'paused') {
      this.bbaudio.pause();
    } 
    this.currentTrack = trackNumber;
    this.log('func: loadTrack: loaded ' + source);
  };


  // Load next track in playlist
  BBPlayer.prototype.loadNext = function () {
    this.log('func: loadNext');
    var trackCount = this.bbaudio.getElementsByTagName("source").length;
    var newTrack   = ((1 + this.currentTrack) % trackCount);
    if (newTrack <= this.currentTrack && !this.repeat) {
      this.state = "paused";
    }
    this.loadTrack(newTrack);
  };


  // Load previous track in playlist
  BBPlayer.prototype.loadPrevious = function () {
    this.log('func: loadPrevious');
    var trackCount = this.bbaudio.getElementsByTagName('source').length;
    var newTrack = (this.currentTrack + (trackCount - 1)) % trackCount;
    this.loadTrack(newTrack);
  };


  // Set up event handlers for audio element events
  BBPlayer.prototype.setAudioEventHandlers = function () {

    var self = this;
    self.log('func: setAudioEventHandlers');

    self.bbaudio.addEventListener('abort', function () {
      self.log('event: audio abort');
    });

    // Update display and continue play when song has loaded
    self.bbaudio.addEventListener('canplay', function () {
      self.log('event: audio canplay');
      if (self.state === 'playing' && this.paused) {
        this.play();
      }
      self.updateDisplay();
    });

    self.bbaudio.addEventListener('canplaythrough', function () {
      self.log('event: audio canplaythrough');
    });

    self.bbaudio.addEventListener('durationchange', function () {
      self.log('event: audio durationchange');
    });

    self.bbaudio.addEventListener('emptied', function () {
      self.log('event: audio emptied');
    });

    // Load next track when current one ends
    self.bbaudio.addEventListener('ended', function () {
      self.log('event: audio ended');
      self.loadNext();
    });

    self.bbaudio.addEventListener('error', function () {
      self.log('event: audio error');
    });

    self.bbaudio.addEventListener('loadeddata', function () {
      self.log('event: audio loadeddata');
    });

    self.bbaudio.addEventListener('loadedmetadata', function () {
      self.log('event: audio loadedmetadata');
    });

    self.bbaudio.addEventListener('loadstart', function () {
      self.log('event: audio loadstart');
    });

    self.bbaudio.addEventListener('pause', function () {
      self.log('event: audio pause');
    });

    self.bbaudio.addEventListener('play', function () {
      self.log('event: audio play');
    });

    self.bbaudio.addEventListener('playing', function () {
      self.log('event: audio playing');
    });

    self.bbaudio.addEventListener('progress', function () {
      self.log('event: audio progress');
    });

    self.bbaudio.addEventListener('ratechange', function () {
      self.log('event: audio ratechange');
    });

    self.bbaudio.addEventListener('seeked', function () {
      self.log('event: audio seeked');
    });

    self.bbaudio.addEventListener('seeking', function () {
      self.log('event: audio seeking');
    });

    self.bbaudio.addEventListener('stalled', function () {
      self.log('event: audio stalled');
    });

    self.bbaudio.addEventListener('suspend', function () {
      self.log('event: audio suspend');
    });

    self.bbaudio.addEventListener('timeupdate', function () {
      // self.log('event: audio timeupdate');
      self.updateDisplay();
    });

    self.bbaudio.addEventListener('volumechange', function () {
      self.log('event: audio volumechange');
    });

    self.bbaudio.addEventListener('waiting', function () {
      self.log('event: audio waiting');
    });

  };


  // Set up button click handlers
  BBPlayer.prototype.setClickHandlers = function () {

    var self = this;
    self.log('func: setClickHandlers');
    var audioElem = self.bbaudio;

    // Activate fast-forward
    [].forEach.call(
      self.bbplayer.getElementsByClassName('bb-forward'),
      function (el) {
        el.addEventListener('click', function () {
          self.log('event: click .bb-forward');
          self.loadNext();          
        });
      }
    );

    // Toggle play / pause
    [].forEach.call(
      self.bbplayer.getElementsByClassName('bb-play'),
      function (el) {
        el.addEventListener('click', function () {
          self.log('event: click .bb-play');
          if (self.bbaudio.paused) { //(audioElem.paused) {
            stopAllBBPlayers();
            self.bbaudio.play();
            self.state = "playing";
          } else {
            self.bbaudio.pause();
            self.state = "paused";
          }
          self.updateDisplay();
        });
      }
    );

    // Activate rewind
    [].forEach.call(
      self.bbplayer.getElementsByClassName('bb-rewind'),
      function (el) {
        el.addEventListener('click', function () {
          self.log('event: click .bb-rewind');
          var time = audioElem.currentTime;
          if (time > 1.5) {
            audioElem.currentTime = 0;
          } else {
            self.loadPrevious();
          }
        });
      }
    );


    // TODO make debug more "pluggy".
    if (self.bbdebug) {
      self.bbdebug.click(function () {
        $(this).empty();
      });
    }

  };


  // BBPlayer initialisation
  BBPlayer.prototype.init = function () {
    var self = this;
    self.setAudioEventHandlers();
    self.loadSources();
    self.currentTrack = 0;
    self.setClickHandlers();
    self.updateDisplay();
  };


  // Create BBPlayer Object for each element of .bbplayer class
  document.addEventListener('DOMContentLoaded', function() {
    [].forEach.call(
      document.getElementsByClassName("bbplayer"),
      function (el) {
        bbplayers.push(new BBPlayer(el));
      }
    );
  });

}());

Hey, can you set up a codepen with the relevant HTML so we can get a demo? It’ll help us have a broken example to play with and work on a fix for :slight_smile: .

2 Likes

Yes, of course…rs… I had forgotten, sorry ( below ) simple html code. It’s a great player, but no volume control :worried:

<script src="js/bbplayer.js"></script>

 <link rel="stylesheet" href="css/bbplayer.css"/>

      
            <div class="bbplayer">
      
      
              <span class="bb-rewind"></span>      
      
              <span class="bb-play"></span>      
      
              <span class="bb-forward"></span>      
      
              <div class="playerWindow">
            
                <div class="bb-track-display">
            
                  <span class="bb-trackTime">--:--</span>      
      
                  <span class="bb-trackTitle">&nbsp;</span>
            
                  <span class="bb-trackLength">--:--</span>      
      
                </div>
            
                <div class="bb-album-display">      
      
                  <span class="bb-artist">Brian Browne Trio</span> -
      
      
                  <span class="bb-album">Blue Browne</span>

     
      
                </div>

<audio >
      
    <source  src="media/Georgia.mp3" type="audio/mp3">
      
      
                   data-album="Blue Browne"
      
      
                   data-artist="Brian Browne Trio"
      
      
         />
      
      
                    
      
              </audio>
      
 </div>
      

Css:

@charset 'UTF-8';
      
      
        /* 
      
      
        Optional styling for bbplayer elements.
      
      
        */
      
      
        @import url(https://fonts.googleapis.com/css?family=Lato:300italic,700italic,300,700);
      
      
             
      
        .bbplayer {
      
      
          font: 200 16px/1.5 Lato,"Helvetica Neue",Helvetica,Arial,sans-serif;
      
      
          color: #898989;
      
      
          border: 1px solid #E0E0E0;
      
      
          border-radius: 5px;
      
      
          display: inline-block;
      
      
          padding: 5px;
      
      
          box-shadow: 0 0 5px rgba(100,100,100,0.2);
      
      
        }
      
               
      
        .bb-play {
      
      
          display: inline-block;
      
      
          vertical-align: middle;
      
      
          height: 32px;
      
      
          width:  32px;
      
      
          border: 6px solid #CFCFCF;
      
      
          border-radius: 50%; 
      
      
          background: transparent; 
      
      
          background-image: url('../images/play.png');
      
      
          background-repeat: no-repeat;
      
      
          background-position: 7px center;
      
      
          cursor: pointer;
      
      
        }            

      
      
        .bb-playing {
      
      
          vertical-align: middle;
      
      
          background-image: url('../images/pause.png');
      
      
          background-position: center center;
      
      
        }
                   
      
        .bb-forward {
      
      
          vertical-align: middle;
      
      
          display: inline-block;
      
      
          height: 32px;
      
      
          width:  32px;
      
      
          background: transparent;
      
      
          background-image: url('../images/forward.png');
      
      
          background-position: center;
      
      
          background-repeat: no-repeat;
      
      
          cursor: pointer;
      
      
        }    
        

           
        .bb-rewind {
      
      
          vertical-align: middle;
      
      
          display: inline-block;
      
      
          height: 32px;
      
      
          width:  32px;
      
      
          background: transparent;
      
      
          background-image: url('../images/rewind.png');
      
      
          background-position: center;
      
      
          background-repeat: no-repeat;
      
      
          cursor: pointer;
      
      
        }  
      
             
      
        .bb-trackTime {
      
      
          display: inline-block;
      
      
          vertical-align: top;
      
      
          font-size: 14px;
      
      
        }    
              
      
        .bb-trackLength {
      
      
          display: inline-block;
      
      
          vertical-align: top;
      
      
          font-size: 14px;
      
      
        }        
     
      
        .bb-trackTitle {
      
      
          display: inline-block;
      
      
          vertical-align: top;
      
      
          font-weight: bold;
      
      
          width: 8em;
      
      
          overflow: hidden;
      
      
          text-align: center;
      
      
        }           

      
      
        .bb-artist {
      
      
          font-size: 14px;
      
      
        }       
              
      
        .bb-album {
      
      
          font-size: 14px;
      
      
        }            

      
      
        .bb-albumCover {
      
      
          height: 38px;
      
      
          width: 38px;
      
      
          line-height: 38px;
      
      
          vertical-align: top;
      
      
          background: #999999;
      
      
          border: 1px solid #666666;
      
      
          box-shadow: 0 0 5px rgba(0,0,0,0.3);
      
      
          margin-left: 5px;
      
      
          display: inline-block;
      
      
        }    
             
      
        .bb-debug {
      
      
          height:10em;
      
      
          width: 19em;
      
      
          border: 1px solid #DDD;
      
      
          border-radius: 5px;
      
      
          margin: 10px;
      
      
          padding: 10px;
      
      
          overflow: auto;
      
      
          font-weight: normal;
      
      
          font-size: 14px/1.5;
      
      
        }     
              
      
        .bbplayer div.playerWindow {
      
      
          display: inline-block;
      
      
          vertical-align: middle;
      
      
          line-height: 20px;
      
      
          text-align: center;
      
      
          border-radius: 3px;
      
      
          border: 1px solid #CFCFCF;
      
      
          padding: 5px;
      
      
          box-shadow: inset 0 0 15px rgba(100,100,100,0.1);
      
      
          background: #EFEFEF;
      
      
        }   
           

      
      
        @media all and (max-width: 480px) {
      
                
      
          .bbplayer {
      
      
            font: 200 14px/1.5 Lato,"Helvetica Neue",Helvetica,Arial,sans-serif;
      
      
            color: #898989;
      
      
            display: inline-block;
      
      
          }             

      
      
          .bb-trackTitle {
      
      
            width: 6em;
      
      
          }    
            

      
      
          .bb-track-display {
      
      
            font-size: 12pt;
      
      
          }             

      
      
          .bb-album-display {
      
      
            display: none;
      
      
          }
                    
      
          .bb-album {
      
      
            font-size: 12px;
      
      
          }    
             
      
          .bb-trackLength {
      
      
            display: none;
      
      
          }       
        

      
      
        }

If my understanding is correct, it isn’t that the code is broken (though it may be) but that ultrabrify wants to modify the code so that a volume control is an option.

Yes…yes…Mittineague, exact ! The complet code: https://github.com/73rhodes/bbplayer

There’s only the one JavaScript file, so I guess the easiest way would be to hack that file.

It looks like the HTML would need something like

<span class="bb-volume">--:--</span>

then inside

  BBPlayer.prototype.setClickHandlers = function () {

there could be a

    // Change Volume 
    [].forEach.call(
      self.bbplayer.getElementsByClassName('bb-volume'),
      function (el) {
        el.addEventListener('click', function () {
          self.log('event: click .bb-volume');
          // code to do volume stuff
        });
      }
    );

:disappointed: Unfortunately this change did not have any effect on increasing or decreasing the volume. I believe that for this, a new function in the JS file should be created ( increasing or decreasing the volume ). Then configured via css and html, equal to the player button that already exists, and this I do not know how to do.

Look the player demo in action ( no volume control ):

http://73rhodes.github.io/bbplayer/

Replace the <audio loop> section with:

<audio loop id="myAudio">
  <source src="http://73rhodes.github.io/bbplayer/media/Blue Browne.ogg" type="audio/ogg" data-album="Blue Browne" data-artist="Brian Browne Trio" data-image="media/Blue Browne small.jpg">
  <source src="http://73rhodes.github.io/bbplayer/media/Georgia.ogg" type="audio/ogg" data-album="Blue Browne" data-artist="Brian Browne Trio" data-image="media/Beatles small.jpg" />
  </audio>
  <br><br><button onclick="getVolume()" type="button">What is the volume?</button>
    <button onclick="setHalfVolume()" type="button">Set volume to 0.2</button>
    <button onclick="setFullVolume()" type="button">Set volume to 1.0</button>
    <br>

Then put the following script just aboave the </body> tag:

<script type="text/javascript">
   var aud = document.getElementById("myAudio");
   function getVolume() { alert(aud.volume); }  
   function setHalfVolume() { aud.volume = 0.2; }  
   function setFullVolume() { aud.volume = 1.0; }
  // 
  </script>

This will give you three buttons: the first lets you check the current audio volume, the second lets you set the volume to 20% and the third lets you set it to 100%. It should not be too hard for you to modify tthis to give the functionality you are seeking.

Ok, thanks, but is it possible to directly change the JS file, include this function ? As Mittineague suggested.
It would be something cleaner, without hacks.

It is simply a matter of adding the JS to the existing file. I am sure that you can do it if you try.

1 Like

Audio player has its own “volume” properly which can be controlled with jQuery as below:

function volumeUp(){
var volume = $(“.audioDemo”).prop(“volume”)+0.2;
if(volume >1){
volume = 1;
}
$(“.audioDemo”).prop(“volume”,volume);
}

function volumeDown(){
var volume = $(“.audioDemo”).prop(“volume”)-0.2;
if(volume <0){
volume = 0;
}
$(“.audioDemo”).prop(“volume”,volume);
}
We need to keep checking whether volume reaches its largest or minimum value, otherwise JavaScript exception error will be thrown.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.