play a track using font awesome icon - javascript

Is it possible to play a song using a font awesome icon, for example on the left will be the song name(mp3) and just to right of the track name will be a play font awesome icon, is it possible for a user to click on the play icon and the track starts playing and they can pause it and stop it
There will be about 10 tracks in the list
Has anyone got a sample code or a link to something similar please? I am guessing it will need some sort of javascript for the icons to be able to play, pause and stop
I found this code: http://jsfiddle.net/7341jxv6/2/ but am trying to amend it to use the font awesome play and pause icons instead of the text play and pause
My updated code is below
<audio id="audio1" src="tracks/ub40-ska/kingston-town.mp3"></audio>
<audio id="audio2" src="tracks/ub40-ska/homely-girl.mp3"></audio>
<audio id="audio3" src="tracks/ub40-ska/red-red-wine.mp3"></audio>
<audio id="audio4" src="tracks/ub40-ska/one-in-ten.mp3"></audio>
<div class="play" id="btn1"><i class="fa fa-play-circle" aria-hidden="true"></i></div>
<div class="play" id="btn2"><i class="fa fa-play-circle" aria-hidden="true"></i></div>
<div class="play" id="btn3"><i class="fa fa-play-circle" aria-hidden="true"></i></div>
<div class="play" id="btn4"><i class="fa fa-play-circle" aria-hidden="true"></i></div>
<script>
$('.play').click(function(){
var $this = $(this);
var id = $this.attr('id').replace(/btn/, '');
$this.toggleClass('active');
if($this.hasClass('active')){
$this.addClass('fa-pause-circle');
$('audio[id^="audio"]')[id-1].play();
} else {
$this.removeClass('fa-play-circle');
$('audio[id^="audio"]')[id-1].pause();
}
});
</script>
If I click on the play icon, it does play but the icon then disappears but if I click in the same place, it does pause the music

You can write click listener for the fa-icon;
DOM looks like this
<div class="play-tab">
<div class="track-name">Some Track Name<div>
<span class="icons"><i class="fa fa-play"/><span>
<div>"
JQuery
$(".play-tab").on("click" , "i", function(e){//fetch song id and play})

if you use the same button then you need a function that will change the icon and stop/play music
var myAudio = document.getElementById('media_audio');
var icon = document.getElementById('toglePlayPause');
var togglePlayPauseButton = document.getElementById('media_controls_play-pause-button');
//Event listener for the play button
togglePlayPauseButton.addEventListener("click", function() {
if ( myAudio.paused || myAudio.ended) {
if ( myAudio ) {
myAudio.title = 'Play';
icon.className = "fa fa-play";
}
myAudio.play();
} else {
if ( myAudio ) {
myAudio.title = 'Pause';
icon.className = "fa fa-pause";
}
myAudio.pause();
}
});
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class="media_player">
<audio id="media_audio" >
Your browser does not support the audio tag.
</audio>
<div id='media_controls' >
<button
id="media_controls_play-pause-button"
class='icon'
title="Pause">
<i id="toglePlayPause" class="fa fa-pause"></i>
</button>
</div>
</div>

I have updated the code above as getting bit closer but got the issue of the icon disappearing after clicking play

You try to change icon on button element but the icon is on "i" tag.
To fix the bug you need to add a small fixes to your code
$('.play').click(function(){
var $this = $(this);
var id = $this.attr('id').replace(/btn/, '');
$this.toggleClass('active');
if($this.hasClass('active')){
$this.find("i").removeClass('fa-play-circle');
$this.find("i").addClass('fa-pause-circle');
$('audio[id^="audio"]')[id-1].play();
} else {
$this.find("i").removeClass('fa-pause-circle');
$this.find("i").addClass('fa-play-circle');
$('audio[id^="audio"]')[id-1].pause();
}
});

Related

Javascript play/pause toggle functionality

I am trying to add play/pause toggle functionality to a single button for an mp3 player project where the play button will turn to a "||" icon when music is playing and will revert to the play button when the music is paused by only using vanilla JavaScript. I have tried implementing an if-else statement which seems to be commonly used for this type of functionality, but the icon will only change to the "||" icon when the song is played, but will not pause and change to the play icon when clicked again. I have tried creating a separate function for the task of pausing the song, but still not getting the desired result.
var playButton = document.querySelector('#play-button');
var songArtist = document.querySelector('.song-artist');
var songTitle = document.querySelector('.song-name');
var stateIcon = document.querySelector('#stateicon');
var trackList = [ {
'Songartist': 'Artist1',
'Songtitle': 'Dance',
'songfile': 'Dance.mp3'
},
{
'Songartist': 'Artist2',
'Songtitle': 'Fight',
'songfile': 'Battle.mp3'
}
];
var currentSong = 0;
var song = new Audio();
function playSong() {
song.src = trackList[currentSong].songfile;
songArtist.innerText = trackList[currentSong].Songartist;
songTitle.innerText = trackList[currentSong].Songtitle;
if (song.paused) {
stateIcon.className = 'fas fa-pause';
song.play();
} else {
stateIcon.className = 'fas fa-play';
song.pause();
}
}
<body>
<div class="screen">
<div class="song-info-text">
<p class="song-artist">Some text</p>
<p class="song-name">Some more text</p>
</div>
</div>
<div class="mp3-buttons">
<button class="button" type="button" name="button"><i class="fas fa-step-backward"></i></button>
<button id="play-button" onclick="playSong()"><i id="stateicon" class="fas fa-play"></i></button>
<button onclick="nextSong()" class="button" type="button" name="button"><i class="fas fa-step-forward"></i></button>
</div>
<script src="index.js" charset="utf-8"></script>
</body>
The snipped provided is incomplete (no element has the class "song-artist", for one). I'd suggest looking at your javascript dev console for any errors, first. Otherwise, it could be that setting the src of your audio element is resetting your audio's play state. You could try only setting the src if it's different from that of the current track.

Javascript MP3 player play/pause toggle functionality

I'm trying to develop a simple mp3 player with play/pause toggle functionality where the play button turns to a "||" icon when music is playing and reverts to the play button when the music is paused by using purely vanilla Javascript. I have viewed other posts regarding this matter, but none of them have helped me with the way I currently have my code structured.
var playButton = document.querySelector('#play-button');
var firstSong = new Audio('CloudDance.mp3');
var trackList = [firstSong];
function currentSong() {
for(var i=0; i<trackList.length; i++) {
var songID = document.querySelector('#stateicon');
if (trackList[i].paused) {
songID.id = 'fas fa-pause';
trackList[i].play();
} else {
songID.addEventListener('click', ) = 'fas fa-play';
trackList[i].pause();
}
}
}
<body>
<div class="screen">
<div class="song-info-text">
<p class="song-artist">Some text</p>
<p class="song-name">Some more text</p>
</div>
</div>
<div class="mp3-buttons">
<button class="button" type="button" name="button"><i class="fas fa-step-backward"></i></button>
<button id="play-button" onclick="currentSong()" type="button" name="button"><i id="stateicon" class="fas fa-play"></i></button>
<button class="button" type="button" name="button"><i class="fas fa-step-forward"></i></button>
</div>
<script src="index.js" charset="utf-8"></script>
</body>
All you need to do is set the class name depending on what you want. Here is your example with the fix.
songID.className = 'fas fa-pause';
Here is the sample code used in the JSFiddle link below
var playButton = document.querySelector('#play-button');
var firstSong = new
Audio('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3');
var trackList = [firstSong];
function currentSong() {
for(var i=0; i<trackList.length; i++) {
var songID = document.querySelector('#stateicon');
if (trackList[i].paused) {
songID.className = 'fas fa-pause'; // Notice how we set className
trackList[i].play();
} else {
songID.className = 'fas fa-play'; // Notice how we set className
trackList[i].pause();
}
}
}
I also updated font-awesome css url in html to make sure the fonts would work properly. This is another part of the fix
<header>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css"/>
</header>
JSFiddle Working Example
NOTE: You may end up running into issues later as you will end up playing multiple files at the same time with the way you have the for loop. So just keep in mind that you need to know which song it's currently playing so that you can properly pause or play that same song. And switch the current song when hit forward or backwards depending on the button pressed.

Javascript does not run without this broken component

When setting this up I did not initially notice that the third var declaration had an incorrect method call. The page functioned as I hoped and all was well.
Later I noticed that there was an error clocked in the inspector. I take out the offending line and all should be good- but the script does not work anymore. Strange. So I fix it and change getElementId('close') to the correct getElementById('close') and it the script as a whole still does not work.
This indicates that the script needs the broken component to properly function.
Be aware that the part that does not work anymore is openModal(). The audio.setAttribute() and audio.play() are in the same block and still work, so that is good.
I do not actually need a var close since the closeFunc() is called automatically onclick.
My html:
<div id='myModal' class='modal'>
<div id='modal-content'>
<span onclick='closeFunc()' id='close'>close x</span>
<object id='pdf-enter' data='' type='application/pdf'><p id='fallback-text'>Your browser does not support this media. You can download it <a id='dl-link' href=''>here.</p></a></object>
</div>
</div>
<div class='aud'>
<audio id='paudio' src='../../music/Available Now.mp3' controls='controls' preload="metadata">Your browser does not support the <code>audio</code>element.</audio>
<p id='audio-metadata'></p>
</div>
. . .
<li><a href='#0' class='title'>Sassthefrass <i onclick='audiosass()' class="fa fa-play-circle-o fa-fw" aria-label='Listen to music.'></i> <i onclick='openModal(), sass()' class='fa fa-file-pdf-o fa-fw' aria-label='View the sheet music.'></i></a>
</li>
and the javascript
<script defer async>
var modal = document.getElementById('myModal');
var here = document.getElementById('dl-link');
var close = document.getElementId('close');
var pdf = document.getElementById('pdf-enter');
function openModal() {
modal.style.display = "block";
}
function sass() {
pdf.setAttribute('data', '../../scores/Sassthefrass Perusal.pdf');
here.setAttribute('href', '../../scores/Sassthefrass Perusal.pdf');
}
function closeFunc() {
modal.style.display = "none";
}
</script>
When correctly working, clicking on the pdf FA icon opens a modal with a pdf showing the sheet music. When the code is 'error free', it does not do this anymore.
This is a reduced version, but you can see the entire thing in action at cortlandmahoney.com/pages/comp/acoustic.html. Be aware the site is still in development, but is near completion.
Close is not defined as an ID.
You have to define as 'close x'
and at your javascript you can assign function like :
document.getElementById('foo').onclick=function(){
alert("You have clicked close");
};
I looked at your website link and there is one more exception regarding jquery.
In jquery you have to define as $('#id').onclick() function to assign onclick function.
Your code worked fine on my end with a little modification. Unless I don't I understand you.
<div id='myModal' class='modal'>
<div id='modal-content'>
<span onclick='closeFunc()'>close x</span>
<object id='pdf-enter' data='' type='application/pdf'><p id='fallback-text'>Your browser does not support this media. You can download it <a id='dl-link' href=''>here.</p></a></object>
</div>
</div>
<div class='aud'>
<audio id='paudio' src='../../music/Available Now.mp3' controls='controls' preload="metadata">Your browser does not support the <code>audio</code>element.</audio>
<p id='audio-metadata'></p>
</div>
. . .
<li><i onclick='audiosass()' class="fa fa-play-circle-o fa-fw" aria-label='Listen to music.'>audiosass</i> <i onclick='openModal(), audiosass()' class='fa fa-file-pdf-o fa-fw' aria-label='View the sheet music.'>open</i>
</li>
<script defer async>
var modal = document.getElementById('myModal');
var here = document.getElementById('dl-link');
var close = document.getElementById('close');
var pdf = document.getElementById('pdf-enter');
function openModal() {
modal.style.display = "block";
}
function audiosass() {
pdf.setAttribute('data', '../../scores/Sassthefrass Perusal.pdf');
here.setAttribute('href', '../../scores/Sassthefrass Perusal.pdf');
}
function closeFunc() {
modal.style.display = "none";
}
</script>

Why aren't my HTML5 video control buttons working with Javascript?

I am working on a project using <video>, trying to make external HTML buttons play/pause, rewind slow, rewind fast, and fast forward control a video using JavaScript. I have the buttons appearing where I want them, but when I try to use them in the browser, they don't do anything to control the video, and the play button doesn't switch to pause and vice versa. I've tried for hours, looking all over the Web to find anything that I can use to help. Most solutions I find are using jQuery which I understand is easier, but it's not what I need. I just want to do it using pure JavaScript so I can better understand it. Included is my existing code. Any help on how I can get them to work would be appreciated!
HTML:
<script src="sample.js"></script>
<div class="jumbotron">
<div class="container">
<video id="video" poster="images/art/preview.png" width="100%" controls>
<source src="images/art/sample.mp4" type="video/mp4; codecs="avc1.42E01E, mp4a.40.2"">
<source src="images/art/sample.webm" type="video/webm; codecs="vp8, vorbis"">
<source src="images/art/sample.ogv" type="video/ogg; codecs="theora, vorbis"">
Your browser does not support HTML5 video
</video>
<div id="buttonbar">
<button type="button" id="fastBck">
<span class="glyphicon glyphicon-fast-backward"></span>
</button>
<button type="button" id="rew">
<span class="glyphicon glyphicon-backward"></span>
</button>
<button type="button" id="play-pause">
<span class="glyphicon glyphicon-play"></span>
</button>
<button type="button" id="fastFwd">
<span class="glyphicon glyphicon-fast-forward"></span>
</button>
</div>
</div>
</div>
JavaScript:
window.onload = function() {
var video = document.getElementById("video");
var playButton = document.getElementById("play-pause");
var rewButton = document.getElementById("rew");
var fastBckButton = document.getElementById("fastBck");
var fastFwdButton = document.getElementById("fastFwd");
}
playButton.addEventListener("click", function(){
if (video.paused==true) {
video.play();
playButton.className="glyphicon glyphicon-pause";
} else{
video.pause();
playButton.className="glyphicon glyphicon-play";
}
})
rewButton.addEventListener("click", function(){
//not sure exactly how to use currentTime to rewind, or fast forward
})
let the browser pick the right codecs for your video
you defined your variables out of scope (you've encapsulated them inside the onload function)
window.onload = function() {
var video = document.getElementById("video");
var playButton = document.getElementById("play-pause");
var rewButton = document.getElementById("rew");
var fastBckButton = document.getElementById("fastBck");
var fastFwdButton = document.getElementById("fastFwd");
playButton.addEventListener("click", function(){
if (video.paused===true) {
video.play();
playButton.className="glyphicon glyphicon-pause";
} else{
video.pause();
playButton.className="glyphicon glyphicon-play";
}
});
rewButton.addEventListener("click", function(){
//not sure exactly how to use currentTime to rewind, or fast forward
});
};
#import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css");
<div class="jumbotron">
<div class="container">
<video id="video" width="100%" controls>
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4">
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.webm" type="video/webm">
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.ogv" type="video/ogg">
Your browser does not support HTML5 video
</video>
<div id="buttonbar">
<button type="button" id="fastBck"><span class="glyphicon glyphicon-fast-backward"></span></button>
<button type="button" id="rew"><span class="glyphicon glyphicon-backward"></span></button>
<button type="button" id="play-pause"><span class="glyphicon glyphicon-play"></span></button>
<button type="button" id="fastFwd"><span class="glyphicon glyphicon-fast-forward"></span></button>
</div>
</div>
</div>
Good luck with the fast forward and your other methods
window.onload = function() {
var video = document.getElementById("video");
var playButton = document.getElementById("play-pause");
var rewButton = document.getElementById("rew");
var fastBckButton = document.getElementById("fastBck");
var fastFwdButton = document.getElementById("fastFwd");
playButton.addEventListener("click", function(){
if (video.paused==true) {
video.play();
playButton.className="glyphicon glyphicon-pause";
} else{
video.pause();
playButton.className="glyphicon glyphicon-play";
}
})
rewButton.addEventListener("click", function(){
//not sure exactly how to use
currentTime to rewind, or fast forward
})
}
Move listeners inside onload function. Listeners won't be attached until the page is loaded. Respect for wanting to use vanilla JS, however unnecessary.

Need to mute audio and change image with JS

I am trying to create a toggle switch for the audio that replaces the icon dependent on the state. Here is my code (that is not working):
<div id="bgAudioControls">
<a href="#" onclick="muteSound()">
<img id="mute" src="img/sound-off.svg" width="64" height="64" alt="Sound Off" />
</a>
<audio id="bgAudio" autoplay loop preload src="ogg/epic-lead.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>
</div>
<script language="javascript">
function muteSound() {
if (document.getElementById("mute").src == "img/sound-off.svg")
{
document.getElementById("unmute").src = "img/sound-on.svg";
document.getElementById('bgAudio').muted = true;
}
else
{
document.getElementById("mute").src = "img/sound-off.svg";
document.getElementById('bgAudio').muted = false;
}
}
</script>
I am positive I am overlooking something SUPER simple.. Any help appreciated.
A live view of the whole code in action can be seen at http://arc.adamroper.com
The below code works - albeit as two buttons, not a toggle.
Mute
Unmute
UPDATE : working FIDDLE
What says #Stasik is :
You have to remove id="mute" from the <a> tag and put it in the <img> tag
Like this:
<img id="mute" src="img/sound-off.svg" />
UPDATE
to play/pause try this found here
COMPLETE CODE
HTML
<div id="bgAudioControls">
<a href="#" >
<img id="mute" src="img/sound-off.svg" width="64" height="64" alt="Sound Off" />
</a>
<audio id="bgAudio" autoplay loop preload src="ogg/epic-lead.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>
</div>
JAVASCRIPT
$(function() {
$("#mute").click(function(e) {
e.preventDefault();
var song = $('audio')[0]
if (song.paused){
song.play();
document.getElementById("mute").src = "img/sound-on.svg";
}else{
song.pause();
document.getElementById("mute").src = "img/sound-off.svg";
}
});
});
Accessing ".src" of the mute element is not correct, since src is the attribute of the child of the mute element. Assign id="mute" to the element directly for a quick fix.

Categories

Resources