Randomise the play start point in html5 Audio on toggle - javascript

When the play button is clicked I want the mp3/ogg file to start playing from different randomised points.
There's only one button and no visible player for the user to toggle round. It's meant to be like a radio effect.
I am quite new to javascript so need a bit of help. I think I need to have a bit of code that tells it to skip 10-30s randomly through the file. But not sure how to go about it.
Code here:
<a onclick="javascript:toggleSound();"><li><i class="fa fa-play-circle" aria-hidden="true"></i></li></a>
<audio id="audio" preload="auto">
<source src="audio/filename.mp3" type="audio/mpeg"/>
<source src="audio/filename.ogg" type="audio/ogg"/>
function toggleSound() {
var audioElem = document.getElementById('audio');
if (audioElem.paused)
audioElem.play();
else
audioElem.pause();

Try this:
function toggleSound() {
var audioElem = document.getElementById('audio');
if (audioElem.paused) {
audioElem.currentTime = parseInt(Math.random() * 20) + 10;
audioElem.play();
}
else
audioElem.pause();
}

Related

How to use vid.onended to detect when a video is done playing using javascript

I am trying to create an HTML video playlist and currently I am using vid.onended to detect when a video is done playing (based of the current video src) and then play the next video when the video ends. This works perfectly for the first video but for some reason it never plays the second video and jumps straight to the third video.
My code:
//add video playlist functionality to auto play next video based on id
var vid = document.getElementById("urlVideo");
vid.onended = function() {
var video0 = "http://techslides.com/demos/sample-videos/small.mp4";
var video1 = "https://media.w3.org/2010/05/sintel/trailer.mp4";
var video2 = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"
if (vid.src = video0) {
vid.src = video1;
}
if (vid.src = video1) {
vid.src = video2;
}
};
<video id="urlVideo" width="100%" height="460" controls autoplay>
<source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
What am I doing wrong?
Edit:
Answer by Alen Toma works perfectly.
I Also managed to do it according to the current video source based on a comment by Quentin, For anyone else looking for how to do it explicitly with the current video source as the variable/condition, please see
https://jsfiddle.net/redlaw/qjb5h7e9/9/
I did make a small example below, it should help.
Have a look at this JSFiddle.
//add video playlist functionality to auto play next video based on id
var videoSrc = [
"https://media.w3.org/2010/05/sintel/trailer.mp4",
"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"
]
var vid = document.getElementById("urlVideo");
var index = 0;
vid.addEventListener("ended", function() {
var currentSrc = videoSrc[index];
index += 1;
if (index >= videoSrc.length)
index = 0; // Make Loop and jump to the first video
vid.src = currentSrc;
vid.play();
console.log(currentSrc)
}, true);
<video id="urlVideo" controls autoplay>
<source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
</video>
you must use an event listener for your video player like this code:
var vid = document.getElementById("urlVideo");
vid.addEventListener("ended", function() { /* your code*/ }, true);

Javascript onended is detecting the end of the video

Everything in my code works. It just doesn't switch to the next song/video after finishing the current one. I have tried adding an onended event handler (in the tag and in JavaScript) but failed. I also tried jQuery but it did't work. For some reasons it doesn't change songs at the end of the song. Instead, it will replay the same song over and over again.
<video id="vid" src="main/" playsinline autoplay loop>
<script>
var video = document.currentScript.parentElement;
video.volume = 0.1;
var lastSong = null;
var selection = null;
var playlist = ["main/songn.mp4", "main/songl.mp4", "/main/songt.mp4", "/main/songf.mp4"]; // List of Songs
var video = document.getElementById("vid");
video.autoplay=true;
video.addEventListener("ended", selectRandom);
function selectRandom(){
while(selection == lastSong){
selection = Math.floor(Math.random() * playlist.length);
}
lastSong = selection;
video.src = playlist[selection];
}
selectRandom();
video.play();
</script>
</video>
You just need to remove the loop parameter from the video tag if you want to trigger the end event (doc):
<video id="vid" src="main/" playsinline autoplay>
(Your code will handle the loop by loading a new song when one ended.)
BTW, keep var video = document.getElementById("vid"); to refer to your <video> tag, it's shorter and cleaner than the first declaration.

Cycle through audio using js

I'm trying to use a button to change the audio track to 1 of 2 being played in the browser, however, the method I found switches to the second track but doesn't change the audio played afterwards, it only restarts the second track. Here's my code:
function loadSong(){
var player=document.getElementById('player');
var source1=document.getElementById('player');
var source2=document.getElementById('player');
source1.src='/audio/mac+.mp3';
source2.src='/audio/mac-slowed.mp3';
player.load(); //just start buffering (preload)
player.play(); //start playing
}
HTML
<audio id="player" autoplay="autoplay" preload="auto" loop="loop">
<source id="source1" src="/audio/mac+.mp3" type="audio/mpeg">
<source id="source2" src="" type="audio/mpeg">
</audio>
<button onclick='loadSong()'>Switch the Music!</button>
Based on the information you provided in your original inquiry, this is most likely the best fit for you. Attached is a working JSFiddle for you review. You will need to update the src files with your own locally stored files.
HTML:
<audio id="source1" autoplay="autoplay" loop="loop" src='http://www.stephaniequinn.com/Music/Allegro%20from%20Duet%20in%20C%20Major.mp3'></audio>
<audio id="source2" loop="loop" src='http://www.stephaniequinn.com/Music/Pachelbel%20-%20Canon%20in%20D%20Major.mp3'></audio>
<button id="player">Switch the music to track # 2</button>
Javascript:
var player = document.getElementById('player');
var source1 = document.getElementById('source1');
var source2 = document.getElementById('source2');
player.onclick = function() {
curTrack = this.innerHTML.replace(/Switch the music to track # /, "");
if (curTrack == "1") {
nextTrack = "2";
source1.play();
source2.pause();
source2.currentTime = 0;
} else {
nextTrack = "1";
source2.play();
source1.pause();
source1.currentTime = 0;
}
this.innerHTML = "Switch the music to track # " + nextTrack;
}
You are overwriting the #player element look at your code you are saving the same selector to source1 and source 2 so change the selector of source one to source1 and source2

Sequential playback of audio files overlap using .addEventListener ended

The following code is intended to play a series of short audio files in a sequence, as held in a javascript array named audio_sequence.
an .addEventListener('ended',function()) is used to trigger playback of each audio clip in the sequence.
This works as expected for the first 5 items in the array, playing each in turn, but then the audio elements start to play simultaneously and the sequence becomes jumbled.
I have tried several different approaches all yielding similar results.
Would very much appreciate any insights.
And example of the code running can be found here:
Play Sequence
Here's the javascript:
<script type="text/javascript">
var game_sounds = ["rooms", "bars", "food", "inveraray", "arse"];
var game_sequence = [0,1,2,3,4,0,1,2,3,4,0,1,2,3,4];
var sequence_position = 0;
function play_next(){
if (sequence_position < game_sequence.length){
var audioElement = document.getElementById(game_sounds[game_sequence[sequence_position]]);
audioElement.addEventListener('ended', function(){
sequence_position++;
play_next();
}, true);
audioElement.play();
}
}
function playSequence(){
sequence_position = 0;
var audioElement = document.getElementById(game_sounds[game_sequence[sequence_position]]);
// alert(game_sounds[game_sequence[sequence_position]]);
audioElement.addEventListener('ended', function(){
sequence_position++;
play_next();
},true);
audioElement.play();
}
</script>
& the html is as follows:
<a onClick="javascript:playSequence();" href="#"><h2>Play Sequence</h2></a>
<audio hidden id="rooms" preload="auto">
<source src="/audio/rooms.mp3">
</audio>
<audio hidden id="food" preload="auto">
<source src="/audio/food.mp3" >
</audio>
<audio hidden id="bars" preload="auto">
<source src="/audio/bars.mp3">
</audio>
<audio hidden id="inveraray" preload="auto">
<source src="/audio/inveraray.mp3">
</audio>
<audio hidden id="arse" preload="auto">
<source src="/audio/arse.mp3">
</audio>
What is causing the problem is that you are attaching the same event listener several times to each element, as they are in a loop. In a non particularly elegant but effective workaround, you could remove the listener before attaching it again:
var game_sounds = ["rooms", "bars", "food", "inveraray", "arse"];
var game_sequence = [0,1,2,3,4,0,1,2,3,4,0,1,2,3,4];
var sequence_position = 0;
function play_next(){
if (sequence_position < game_sequence.length){
playSequence();
}
}
function playSequence(){
var audioElement = document.getElementById(game_sounds[game_sequence[sequence_position]]);
// alert(game_sounds[game_sequence[sequence_position]]);
audioElement.removeEventListener('ended', prepareNextAudio);
audioElement.addEventListener('ended', prepareNextAudio, true);
audioElement.play();
}
function prepareNextAudio() {
sequence_position++;
play_next();
}
This code works and stops the playlist when each audio has been played for three times, which I guess is what you needed.

Play multiple audio files sequentially or randomly in background using HTML5 and javascript

I am trying to play 3 audio files (with the possibility of more later) that run in the background. At this point I am simply trying to play them sequentially and have it loop back to the first audio file when the last is played. I believe I have tried almost every solution or combination of functions and I just can't get it to work. I run into one of two problems:
If I try using repetition with each audio stored in the array, the page will successfully play the first then tries to play the next two simultaneously, rather than sequentially. And it certainly does not go back to the first. Furthermore, if you notice in my html, I have a seperate ID for each player. Would it be better to put them all in the sample player ID?
jQuery(document).ready(function (){
var audioArray = document.getElementsByClassName('playsong');
var i = 0;
var nowPlaying = audioArray[i];
nowPlaying.load();
nowPlaying.play();
while(true){
$('#player').on('ended', function(){
if(i>=2){
i=0;
}
else{
i++;
}
nowPlaying = audioArray[i];
nowPlaying.load();
nowPlaying.play();
});
}
});
On the other hand, I can play each sequentially but each play needs to be hardcoded for and I cannot loop back to the first
jQuery(document).ready(function (){
var audioArray = document.getElementsByClassName('playsong');
var i = 0;
var nowPlaying = audioArray[i];
nowPlaying.load();
nowPlaying.play();
$('#player').on('ended', function(){
// done playing
//alert("Player stopped");
nowPlaying = audioArray[1];
nowPlaying.load();
nowPlaying.play();
$('#player2').on('ended', function(){
nowPlaying = audioArray[2];
nowPlaying.load();
nowPlaying.play();
});
});
});
Here is my html
<audio id="player" class = "playsong">
<source src="1.mp3" />
</audio>
<audio id="player2" class = "playsong">
<source src="2.mp3" />
</audio>
<audio id="player3" class = "playsong">
<source src="3.mp3" />
</audio>
I am not terribly familiar with javascript, I am wondering if there is another event trigger function built into JS that I am not using? Some help is greatly appreciated.
HTML
<audio id="song-1" preload class="songs">
<source src="1.mp3" type="audio/mpeg" />
</audio>
<audio id="song-2" preload class="songs">
<source src="2.mp3" type="audio/mpeg" />
</audio>
<audio id="song-3" preload class="songs">
<source src="3.mp3" type="audio/mpeg" />
</audio>
<audio id="song-4" preload class="songs">
<source src="4.mp3" type="audio/mpeg" />
</audio>
JS
jQuery(document).ready(function (){
var audioArray = document.getElementsByClassName('songs');
var i = 0;
audioArray[i].play();
for (i = 0; i < audioArray.length - 1; ++i) {
audioArray[i].addEventListener('ended', function(e){
var currentSong = e.target;
var next = $(currentSong).nextAll('audio');
if (next.length) $(next[0]).trigger('play');
});
}
});

Categories