I want to create an audio playlist that can only play and pause. However, when the user is done listening to the entire song, I want to be able for that user to re-play the song.
Currently, the Javascript playlist only plays and stops the music. My pause button is not really working like a pause button. Not sure where I went wrong. And how exactly can I get the song to automatically re-set to the beginning once the user finishes listening to the song? I would very much appreciate the help on this! I wrote the HTML audio code already and just listed the Java Script below.
<script> // play/pause button
$(function() {
$('#play').click(function(){
$('#pause').attr('src',"media/pause.png");
});
});
$(".playBtn").on('click', function() {
var target = $(this).attr("target");
$("#audio").attr("src",target);
$("#audio").trigger("play");
});
$(".pauseBtn").on('click', function() {
$("#audio").trigger("pause");
});
});
</script>
Audio tags have several events to which you can add listeners. Here is a link to a list of them: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events
The "ended" event triggers when the audio is finished playing, so it could help with resetting the song to the beginning when the audio reaches the end.
$("#audio").on("ended", function () {
this.currentTime = 0;
});
You can use loop attribute at <audio> element to continuously loop single audio source. Substitute caching <audio> DOM element for jQuery object to call .play(), .pause() at click events.
javascript
$(function() {
var audio = $("#audio")[0];
$(".playBtn").on("click", function() {
audio.play()
});
$(".pauseBtn").on("click", function() {
audio.pause()
});
})
html
<audio id="audio" src="/path/to/audio/source" loop autoplay controls></audio>
<button class="playBtn">Play</button>
<button class="pauseBtn">Pause</button>
jsfiddle https://jsfiddle.net/kkf33dpr/
Related
How to add a listener on audio/video start?
I can do it like:
$audio.on("play", function() {
console.log("audio played");
});
where $audio is a jQuery object representing the single DOM audio element.
but it will also run when we resume the video. I want it to run on start only.
One way I can do it is:
$audio.on("play", function() {
if(this.currentTime === 0) {
console.log("audio started);
}
});
but this will run multiple times when we play/pause the audio on the start.
Is there any better way to do this? The listener should only work on audio start and audio replayed, not when the user manually drags the seek bar to the beginning of the source.
Store a flag into the data-* attribute of the targeted element:
const $audio = $('.audio');
$audio.on("play", function() {
if ($(this).data('once-played')) return; // Do nothing if data exists.
// Your code here
console.log("Audio started for the first time");
// Finally, add a flag.
$(this).data('once-played', true);
});
<audio class="audio" src="http://upload.wikimedia.org/wikipedia/en/4/45/ACDC_-_Back_In_Black-sample.ogg" autoplay controls loop></audio>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Actually, it might be sounding confusing because I was under the impression that there could be a possibility that currentTime could still return 0 if we do it in a fraction of seconds. But after reading #freedomn-m, #roko-c-buljan, #rory-mccrossan comments, I got it that it will never be possible that currentTime returns 0 when we play-pause-play the video immediately.
Now, let's say I want to track how many times a user has watched the video. The requirements might sound weird but by watched I only meant started/replayed. It doesn't count if the user manually drags the seek bar to the beginning of the source.
Here is how I implemented it finally using all your points:
const $audio = $('.audio');
$audio.on("play", function() {
if ($(this).data('once-played')) return; // Do nothing if data exists.
// Your code here
console.log("Audio started/replayed");
// Finally, add a flag.
$(this).data('once-played', true);
});
$audio.on("ended", function() {
$(this).data('once-played', false);
});
Im having trouble firing up the audio (playback+pause) on the same page.
My standard HTML5 audio player works perfect and has standard controlls like this:
<play title="Play spoken audio for the visually impaired">▶</play>
<pause title="Pause audio, and press again to resume play">❚❚</pause>
Now imagine you would like to have a simplified alternative play/pause controls elsewhere on the same page. Good idea right? Now my problem is, that if I add a separate more minimalistic play / pause control elsewhere on the page, then the first play/pause buttons dissappear entirely!
<play>▶</play>
<pause>❚❚</pause>
All that I want is to duplicate the functionality of the first play/pause and place them elsewhere on the page, allowing users on mobile to have the play/pause on another location of the page for ease of use.
So in summary, I would like to allow the user to controll the playback from two different places simultaneously. The main one has fancier layout, while the alternative one in location 2 has only play and pause toggle. Both should toggle if either one is pressed. (when play is pressed it shows as a pause button and when pause is pressed it becomes a play button).
What must I change in html and or javascript to achieve this? Thanks in advance!
The javascript looks like this:
window.onload = function(){
var myAudio = document.getElementsByTagName('audio')[0];
var play = document.getElementsByTagName('play')[0];
var pause = document.getElementsByTagName('pause')[0];
function displayControls() {
play.style.display = "block";
}
// check that the media is ready before displaying the controls
if (myAudio.paused) {
displayControls();
} else {
// not ready yet - wait for canplay event
myAudio.addEventListener('canplay', function() {
displayControls();
});
}
play.addEventListener('click', function() {
myAudio.play();
play.style.display = "none";
pause.style.display = "block";
});
pause.addEventListener('click', function() {
myAudio.pause();
pause.style.display = "none";
play.style.display = "block";
});
}
DEMO
So you have the following code...
var myAudio = document.getElementsByTagName('audio')[0];
var play = document.getElementsByTagName('play')[0];
var pause = document.getElementsByTagName('pause')[0];
Step-by-step breakdown...
document.getElementsByTagName('audio')[0]
Get the 0th (1st) element in the document that has the tag name audio.
document.getElementsByTagName('play')[0]
Get the 0th (1st) element in the document that has the tag name play.
Problem #1. You only register the first play button for the code. You must add code for the second play button.
document.getElementsByTagName('pause')[0]
Get the 0th (1st) element in the document that has the tag name pause.
Problem #2. Same problem as #1.
So the solution is:
var audio;
window.onload=function(){
audio=document.getElementsByTagName("audio")[0];
//YOU MUST REGISTER AN EVENT LISTENER FOR EVERY PLAY AND PAUSE BUTTON.
document.getElementsByClassName("playpause")[0].addEventListener("click",playpause);
document.getElementsByClassName("playpause")[1].addEventListener("click",playpause);
}
function playpause(){
var state;
if(audio.paused){
audio.play();
state="Pause";
}else{
audio.pause();
state="Play";
}
for(var i=0;i<document.getElementsByClassName("playpause").length;i++){
document.getElementsByClassName("playpause")[i].innerHTML=state;
}
}
<audio>
<source src="http://www.kozco.com/tech/32.mp3" type="audio/mpeg">
</audio>
<button class="playpause">Play</button>
<button class="playpause">Play</button>
I have a couple of music players in my website, all from a same plugin as
<audio id="player2" src="//filename" type="audio/mp3" controls="controls"></audio>
I want the previous audio player to stop when the user plays audio from another player.
I am a beginner so wish to have an easy explanation.
You need to listen to the play event and run pause on other players.
var audios = document.getElementsByTagName('audio'); // We get a list of all audio elements
audios.forEach(function(player) {
player.addEventListener('play', function() { // We listen for the `play` event on each player
audios.forEach(function(player2) {
if (player !== player2) { // we find other players which don't match the one that started
player2.pause(); // we pause those other players
}
});
});
});
I'm in the early stages of setting up a band site where there are a number of sample audio streams. Each stream is triggered or stopped by separate "Play" and "Pause" buttons. There are also a number of videos on the page which have their own controls. I used the following code for setting up the audio samples:
$("#play0").click(function() {
$("#audio0").trigger('play');
});
$("#pause0").click(function() {
$("#audio0").trigger('pause');
});
The "audio0" ID is for each audio stream (up to "audio9") while "play0" and "pause0" IDs (also up to "play/pause9") are for buttons. How can I make sure that at any one time, only one audio file should be playing (irrespective of whether it is audio or video). In other words, a user cannot trigger more than one audio stream to play simultaneously. Thank you.
Try something like this
var media = $('audio, video');
function pauseAll() {
media.each(function() {
var element = $(this).get(0);
element.pause();
});
}
$("#play0").click(function(){
pauseAll();
$("#audio0")[0].play();
});
How could we make some audio in html5 play after another one has finished?
I have tried with jquery delay() function but it wont work at all, is it possible using pause() in html5 audio with timer instead ? For example, pause('500',function(){});?
Here's a JSLinted, unobtrusive Javascript example demonstrating how to handle and use the ended mediaevent. In your particular situation, you would trigger playback of the second audio file in your ended event handler.
You can use the code below or run the test fiddle.
Click an item in the playlist to begin playback. After one audio ends, the next will begin.
markup: (note the deliberate avoidance of whitespace between <li> elements - this is to simplify traversing the DOM with nextSibling.)
<audio id="player"></audio>
<ul id="playlist"><li data-ogg="http://www.lunerouge.org/sons/sf/LRWeird%201%20by%20Lionel%20Allorge.ogg">Space 1</li><li data-ogg="http://www.lunerouge.org/sons/sf/LRWeird%202%20by%20Lionel%20Allorge.ogg">Space 2</li><li data-ogg="http://www.lunerouge.org/sons/sf/LRWeird%203%20by%20Lionel%20Allorge.ogg">Space Lab</li></ul>
<button id="stop">Stop</button>
script:
// globals
var _player = document.getElementById("player"),
_playlist = document.getElementById("playlist"),
_stop = document.getElementById("stop");
// functions
function playlistItemClick(clickedElement) {
var selected = _playlist.querySelector(".selected");
if (selected) {
selected.classList.remove("selected");
}
clickedElement.classList.add("selected");
_player.src = clickedElement.getAttribute("data-ogg");
_player.play();
}
function playNext() {
var selected = _playlist.querySelector("li.selected");
if (selected && selected.nextSibling) {
playlistItemClick(selected.nextSibling);
}
}
// event listeners
_stop.addEventListener("click", function () {
_player.pause();
});
_player.addEventListener("ended", playNext);
_playlist.addEventListener("click", function (e) {
if (e.target && e.target.nodeName === "LI") {
playlistItemClick(e.target);
}
});
If this is your audio tag:
<audio id="player" src="someAudio.mp3"/>
then adding an event listener to it for the "ended" event will make it possible to change the source and play your next sound.
var audio = document.getElementById("player");
audio.addEventListener("ended", function() {
audio.src = "nextAudio.mp3";
audio.play();
});
I think this answer will help you ...
html5 audio player - jquery toggle click play/pause?
so instead of a click you should use a setTimeout, or a setInterval, which ever you feel more comfortable with to check constantly for the .paused==false I think you might be able to check if it is finished by checking videos's length and compare it with max length, which == end of file.