dcsimg
www.webdeveloper.com
Results 1 to 5 of 5

Thread: Beginner question

  1. #1
    Join Date
    Feb 2017
    Posts
    3

    Question Beginner question

    Ok, i guess I'm going to invoke here somebody's patience since I'm a Javascript beginner.

    Here the story:

    I decided to go into JS building a html5 audio player, so I started editing my html, css and js.
    I basically built a player and styled it and needed some js for my buttons behavior.
    At first I built my player for only 1 (one) track. So I just added some EventListeners to my buttons leading them to my playOrPause or my muteOrUnmute functions, both of them relating to var track1 since it was the only track playing.
    In addition I created a couple of functions to make the progressBar clickable so the user could jump to whatever point in the track.
    Everything was working fine and looking great.
    But what I needed it was a player with a 5 track playlist.
    So I built-it. Created an ordered list and styled it. But now I had to solve some stuff in the JS.
    So I started working.
    Then (and I don't know it was the correct way) i quintuplicated the playOrPause function, one for each track, same with muteOrUnmute functon.
    Made the playlist work creating eventListeners to each <li> and leading them to the right playOrPause function depending of the track.
    All fine.

    BUT

    there is something I DON'T KNOW how to solve:

    The 3 eventListeners: playButton, muteButton and probressBar [all of them ('click')].
    why?
    Because if you have a 1 track player no problem, you lead them to the only playOrPause, muteOrUnmute or clicked bar function you have, track1's.
    But if you have 5 tracks...

    So At the moment this is what I've achieved so far

    And here is the js, if you want html and css just ask for it.

    Thanks a buch in advance.

    Code:
    /*Variables*/
    
    var track1 = document.getElementById('1');
    var track2 = document.getElementById('2');
    var track3 = document.getElementById('3');
    var track4 = document.getElementById('4');
    var track5 = document.getElementById('5');
    
    var piedras = document.getElementById('piedras')
    
    var playButton = document.getElementById ('playButton');
    var speakerButton = document.getElementById('speakerButton');
    
    var fullDuration = document.getElementById('fullDuration');
    var currentTime = document.getElementById('currentTime');
    
    var minutes = parseInt(track1.duration/60);
    var seconds = parseInt(track1.duration%60);
    
    var medidaBarraTotal = 220;
    var defaultBar = document.getElementById('defaultBar');
    var progressBar = document.getElementById('progressBar');
    
    fullDuration.innerHTML = minutes + ':' + seconds
    
    /*Event Listeners*/
    
    playButton.addEventListener('click',playOrPause,false)
    speakerButton.addEventListener('click',muteOrUnmute,false)
    defaultBar.addEventListener('click',clickedBar, false)
    piedras.addEventListener('click',playOrPause,false)
    baiao.addEventListener('click',playOrPause2,false)
    bailecito.addEventListener('click',playOrPause3,false)
    solsticio.addEventListener('click',playOrPause4,false)
    rosa.addEventListener('click',playOrPause5,false)
    
    /*play and pause fucntions for all tracks*/
    
    function playOrPause () {
    	if(!track1.paused && !track1.ended) {
    		track1.pause();
    		playButton.style.backgroundImage = 'url(./images/playButton.png)';
    		windows.clearInterval (updateTime);
    	}
    	else {
    		track1.play() ;
    		track2.pause() ;
    		track2.currentTime = 0;
    		track3.pause() ;
    		track3.currentTime = 0;
    		track4.pause() ;
    		track4.currentTime = 0;
    		track5.pause() ;
    		track5.currentTime = 0;
    		playButton.style.backgroundImage = 'url(./images/pauseButton.png)'
    		updateTime = setInterval (update,500);
    	}
    }
    function playOrPause2 () {
    	if(!track2.paused && !track2.ended) {
    		track2.pause();
    		playButton.style.backgroundImage = 'url(./images/playButton.png)';
    		windows.clearInterval (updateTime);
    	}
    	else {
    		track2.play() ;
    		track1.pause() ;
    		track1.currentTime = 0;
    		track3.pause() ;
    		track3.currentTime = 0;
    		track4.pause() ;
    		track4.currentTime = 0;
    		track5.pause() ;
    		track5.currentTime = 0;
    		playButton.style.backgroundImage = 'url(./images/pauseButton.png)'
    		updateTime = setInterval (update,500);
    	}
    }
    function playOrPause3 () {
    	if(!track3.paused && !track3.ended) {
    		track3.pause();
    		playButton.style.backgroundImage = 'url(./images/playButton.png)';
    		windows.clearInterval (updateTime);
    	}
    	else {
    		track3.play() ;
    		track2.pause() ;
    		track2.currentTime = 0;
    		track1.pause() ;
    		track1.currentTime = 0;
    		track4.pause() ;
    		track4.currentTime = 0;
    		track5.pause() ;
    		track5.currentTime = 0;
    		playButton.style.backgroundImage = 'url(./images/pauseButton.png)'
    		updateTime = setInterval (update,500);
    	}
    }
    function playOrPause4 () {
    	if(!track4.paused && !track4.ended) {
    		track4.pause();
    		playButton.style.backgroundImage = 'url(./images/playButton.png)';
    		windows.clearInterval (updateTime);
    	}
    	else {
    		track4.play() ;
    		track2.pause() ;
    		track2.currentTime = 0;
    		track3.pause() ;
    		track3.currentTime = 0;
    		track1.pause() ;
    		track1.currentTime = 0;
    		track5.pause() ;
    		track5.currentTime = 0;
    		playButton.style.backgroundImage = 'url(./images/pauseButton.png)'
    		updateTime = setInterval (update,500);
    	}
    }
    function playOrPause5 () {
    	if(!track5.paused && !track5.ended) {
    		track5.pause();
    		playButton.style.backgroundImage = 'url(./images/playButton.png)';
    		windows.clearInterval (updateTime);
    	}
    	else {
    		track5.play() ;
    		track2.pause() ;
    		track2.currentTime = 0;
    		track3.pause() ;
    		track3.currentTime = 0;
    		track4.pause() ;
    		track4.currentTime = 0;
    		track1.pause() ;
    		track1.currentTime = 0;
    		playButton.style.backgroundImage = 'url(./images/pauseButton.png)'
    		updateTime = setInterval (update,500);
    	}
    }
    
    /*Mute and unmute function for all tracks*/
    
    function muteOrUnmute () {
    	if(!track1.muted && !track1.ended) {
    		track1.muted = true ;
    		speakerButton.style.backgroundImage = 'url(./images/muteButton.png)'
    	}
    	else {
    		track1.muted = false ;
    		speakerButton.style.backgroundImage = 'url(./images/speakerButton.png)'
    	}
    		
    }
    function muteOrUnmute2 () {
    	if(!track2.muted && !track2.ended) {
    		track2.muted = true ;
    		speakerButton.style.backgroundImage = 'url(./images/muteButton.png)'
    	}
    	else {
    		track2.muted = false ;
    		speakerButton.style.backgroundImage = 'url(./images/speakerButton.png)'
    	}
    		
    }
    function muteOrUnmute3 () {
    	if(!track3.muted && !track3.ended) {
    		track3.muted = true ;
    		speakerButton.style.backgroundImage = 'url(./images/muteButton.png)'
    	}
    	else {
    		track3.muted = false ;
    		speakerButton.style.backgroundImage = 'url(./images/speakerButton.png)'
    	}
    		
    }
    function muteOrUnmute4 () {
    	if(!track4.muted && !track4.ended) {
    		track4.muted = true ;
    		speakerButton.style.backgroundImage = 'url(./images/muteButton.png)'
    	}
    	else {
    		track4.muted = false ;
    		speakerButton.style.backgroundImage = 'url(./images/speakerButton.png)'
    	}
    		
    }
    function muteOrUnmute5 () {
    	if(!track5.muted && !track5.ended) {
    		track5.muted = true ;
    		speakerButton.style.backgroundImage = 'url(./images/muteButton.png)'
    	}
    	else {
    		track5.muted = false ;
    		speakerButton.style.backgroundImage = 'url(./images/speakerButton.png)'
    	}
    		
    }
    
    /*Update function for currentTime and progressBar*/
    
    function update() {
    	if(!track1.ended) {
    		var playedMinutes = parseInt(track1.currentTime/60);
    		var playedSeconds = pad(parseInt(track1.currentTime%60));
    		currentTime.innerHTML = playedMinutes + ':' + playedSeconds;
    		var progressBarSize = parseInt(track1.currentTime*medidaBarraTotal/track1.duration)
    		progressBar.style.width = progressBarSize + "px" ;
    	}
    	else {
    		currentTime.innerHTML = "0.00";
    		playButton.style.backgroundImage = 'url(./images/playButton.png)';
    		progressBar.style.width = "0px";
    		windows.clearInterval (updateTime);
    	}
    }
    
    /*clickedBar function for progressBat being clicked*/
    
    function clickedBar (e) {
    	if(!track1.ended) {
    		var mouseX = e.pageX - defaultBar.offsetLeft;
    		var newTime = mouseX*track1.duration/medidaBarraTotal;
    		track1.currentTime = newTime;
    		progressBar.style.width = mouseX+"px";
    	}
    }
    
    /*pad function for get decimas right in currentTime*/
    
    function pad(d) {
    	return (d<10) ? '0' + d.toString() : d.toString(); 
    }

  2. #2
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    4,361
    You should create a single function for elements that are repeated like your mutes / unmutes, in your script, this would look like, use a style CSS class name to set the desired image, give the buttons used name="" attributes to match the tracks so that the <input name="track1" type="button" value="mute" onclick="toggleMute( this );" >
    Code:
    function toggleMute( btn ) {
        switch( btn.name ){
            case "track1":
                track1.muted = (!track1.muted && !track1.ended) ? false : true;
                speakerButton.style.className = track1.muted ? "mute" : "speaker";
                btn.value = (track1.muted ? "un" :"" ) +"mute";
            break;
    
           case "track2":
                track2.muted = (!track2.muted && !track2.ended) ? false : true;
                speakerButton.style.className = track1.muted ? "mute" : "speaker";
                btn.value = (track1.muted ? "un" :"" ) +"mute";
            break;
        }
    }
    It would help to know the HTML you are using, you are repeating routines so many times it may even be easier to create an audio control system if your HTML was shown.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  3. #3
    Join Date
    Feb 2017
    Posts
    3
    here it is:
    Code:
    <!DOCTYPE html>
    <html>
    <head>
    	<link rel="stylesheet" href="index.css">
    	<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    </head>
    <body>
    	<div id="player">
    		<audio id="1"> 
    			<source src="./mix/1.mp3" type="audio/mp3"/>
    		</audio>
    		<audio id="2"> 
    			<source src="./mix/2.mp3" type="audio/mp3"/>
    		</audio>
    		<audio id="3"> 
    			<source src="./mix/3.mp3" type="audio/mp3"/>
    		</audio>
    		<audio id="4"> 
    			<source src="./mix/4.mp3" type="audio/mp3"/>
    		</audio>
    		<audio id="5"> 
    			<source src="./mix/5.mp3" type="audio/mp3"/>
    		</audio>
    		<nav>
    			<div id="defaultBar">
    				<div id="progressBar"></div>
    			</div>
    			<div id="buttons">
    				<button type="button "id="playButton"></button>
    				<button type="button "id="stopButton"></button>
    				<button type="button "id="speakerButton"></button>
    				<span id="currentTime">0:00</span><span id="barra">/</span><span id="fullDuration">0:00</span>
    			</div>
    		</nav>
    		<div id="playlist">
    			<ol id="lista">
    				<li id="piedras">Piedras del Agua</li>
    				<li id="baiao">Baiao e Modinha</li>
    				<li id="bailecito">Bailecito Urbano</li>
    				<li id="solsticio">Solsticio</li>
    				<li id="rosa">A Don Rosa Toledo</li>
    			</ol>
    			<div id="fondo_lista"></div>
    		</div>
    	</div>
    	<script type="text/javascript" src="index.js"></script>
    </body>
    </html>

  4. #4
    Join Date
    Feb 2017
    Posts
    3
    IT doesn't let me send you the html code, don't know what's wrong. But in my link you can just get the source code.
    thanks a lot in advance

  5. #5
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    4,361
    Tested in Chrome.

    You only use one audio output, when track is changed, the audio element is updated. No track is set to start with, you have to click on a track from the list. If you are looking for automation on playing the whole list, then you would have to adapt the script to automatically select the next track in the audio playlist.

    The elements in the window.onload function DO NOT do what many people do and edit it to put var before the variables, that will kill the script, they need to be global variables.

    HTML Code:
    <!DOCTYPE html>
    <html>
    <head>
    <script>
    // grab audio & display elements when DOM is loaded
    window.onload = function(){
    	// display elements
    	display = {
    		playList: document.getElementById("fondo_lista"), 
    		currentTime: document.getElementById("currentTime"),
    		trackLength: document.getElementById("fullDuration"),
    		progressBar: document.getElementById("progressBar"),
    		volume: document.getElementById("volume")
    	}
    	
    	// grab the audio element
    	audio = {
    		output: document.getElementById("track"),
    		playList:[],
    		display:false
    	}
    	
    	// grab the li element, it contains the track information 
    	playlist = document.getElementById("lista").getElementsByTagName("li"); // each element has data- attributes
    
    	for(var d=0; d<playlist.length; d++){
    		// make li elements click able
    		playlist[d].onclick = function(){ process(this); }
    
    		// grab data-track-src elements & store in an object with track numner, track name
    		audio.playList.push( {track:1+d, src:playlist[d].getAttribute("data-track-src"), name:playlist[d].innerHTML } );
    	}
    		
    }
    /* ********************************************************************** */
    Array.prototype.getTrack = function( tk ){
    	for(var t=0; t<this.length; t++) 
    		if( this[t].track == tk ){
    			return this[t];
    	} 
    	return -1;
    }
    
    Object.prototype.isPlaying = function(){
        return !this.paused && !this.ended && 0 < this.currentTime;
    }
    
    // Playback controls
    function playback( btn ){
    
    		switch( btn.name ){
    			case "play": audio.output.play(); break;
    			case "stop": 	audio.output.pause(); 
    								audio.output.currentTime = 0; 
    								break;
    			case "speaker":  audio.output.muted = !audio.output.muted; break;
    			case "volume": 	if( btn.value == "Volume +") audio.output.volume += audio.output.volume<1 ? 0.1 : 0; 
    									if(btn.value == "Volume -") audio.output.volume -= audio.output.volume>0.1 ? 0.1 : 0;
    								break;
    			}
    
    }
    
    // process is the control centre...
    function process( lnk ){
    	// stop the current playback
    	if( audio.output.isPlaying() ){ 
    		playback( {name:"stop"} );
    		clearInterval( audio.display );
    	}
    				
    	// Get the track information		
    	newTrack = audio.playList.getTrack( lnk.id );
    	
    	// if valid, then start to play back.
    	if( newTrack !=-1 ){
    		display.playList.innerHTML = newTrack.track +" : "+ newTrack.name;
    		audio.output.src =  newTrack.src;
    		audio.output.play();
    		audio.display = setInterval("updateDisplay()",500);
    	}
    
    }
    
    function updateDisplay(){
    	display.volume.innerHTML = Math.floor( audio.output.volume *10 ) / 10; 
    	display.currentTime.innerHTML = Math.floor( audio.output.currentTime );
    	display.trackLength.innerHTML =  Math.floor( audio.output.duration );
    	display.progressBar.innerHTML = (audio.output.currentTime > 0 ? Math.floor( ( audio.output.currentTime / audio.output.duration ) * 100 ) : 0 ) + "%";
    	if( !audio.output.isPlaying() ){ 
    		clearInterval(audio.display);
    	}
    }
    
    </script>
    	
    </head>
    <body>
    	<div id="player">
    		<audio id="track" src="" type="audio/mp3"/></audio>
    		<nav>
    			<div id="defaultBar">
    				<div id="progressBar"></div>
    			</div>
    			<div id="buttons">
    				<form name="buttons" action="javascript:;">
    					<input name="play" type="button" value="playButton" onclick="playback(this);">
    					<input name="stop"  type="button" value="stopButton" onclick="playback(this);">
    					<input name="speaker" type="button" value="speakerButton" onclick="playback(this);">
    					<input name="volume" type="button" value="Volume +" onclick="playback(this);">
    					<input name="volume" type="button" value="Volume -" onclick="playback(this);">
    				</form>
    				<span id="currentTime">0:00</span><span id="barra">/</span><span id="fullDuration">0:00</span><br>
    				Volume: <span id="volume"></span>
    			</div>
    		</nav>
    		<div id="playlist">
    			<ol id="lista">
    				<li id="1"  data-track-src="./Banco_de_Gaia-Sheesha.mp3">Sheesha</li>
    				<li id="2"  data-track-src="./APL-Hypnosystem.mp3">Hypnosystem</li>
    				<li id="3"  data-track-src="./mix/3.mp3">Bailecito Urbano</li>
    				<li id="4"  data-track-src="./mix/4.mp3">Solsticio</li>
    				<li id="5"  data-track-src="./mix/5.mp3">A Don Rosa Toledo</li>
    			</ol>
    			<div id="fondo_lista"></div>
    		</div>
    	</div>
    </body>
    </html>
    The time output for the audio is measured in seconds, this will need to be modified if you want minutes and seconds.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles