How play group of audio files in HTML and JavaScript? - javascript

<html>
<body>
<audio autoplay id ="audio_1" src = "./Dusty.wav"></audio>
<audio loop id = "audio_2" src = "./Dusty3.wav"></audio>
<audio loop id = "audio_3" src = "./Dusty2.wav"></audio>
<!-- <input type = "button" value = "play" onClick="audiofun();" -->
</body>
<script>
// audiofun()
// {
var audio = document.getElementById("audio_1");
var audio2 = document.getElementById("audio_2");
var audio3 = document.getElementById("audio_3");
// audio2.pause();
// audio3.pause();
audio.addEventListener("ended", function () {audio2.play();})
audio2.addEventListener("ended", function () {audio3.play();})
// }
</script>
</html>
When I run this code audio2.play() is continuously playing and audio3.play is not at all playing. can anyone put light on my error... thanks in advance

i feel like your problem comes from the property "loop" in your audio tag. Maybe you should try:
<audio id = "audio_2" src = "./Dusty3.wav"></audio>
<audio id = "audio_3" src = "./Dusty2.wav"></audio>
And add a event listener on your first, then second audio.
var audio = document.getElementById("audio_1");
var audio2 = document.getElementById("audio_2");
var audio3 = document.getElementById("audio_3");
document.getElementById('audio_1').addEventListener('ended',audio_1Handler,false);
function audio_1Handler(e) {
audio2.play();
}
document.getElementById('audio_2').addEventListener('ended',audio_2Handler,false);
function audio_2Handler(e) {
audio3.play();
}
the snippet above is highly inspired of : this post
Hopefully this helps you.
Feel free to ask any further questions !

Related

Hiding HTML5 video sources in div tag id attributes

I’d like to be able to specify my video sources for my toggle button in the HTML document so that I don’t have to include them in the JavaScript code.
I figured out a way to accomplish it by hiding the URLs in div tags as id attributes and then getting them in the JavaScript by their class name. (See below). This seems like a total hack. I’m sure there must be a better way to do this. Any suggestions?
<!DOCTYPE html>
<html>
<body>
<div class="video1" id="http://www.w3schools.com/html/mov_bbb.mp4"></div>
<div class="video2" id="http://www.w3schools.com/html/movie.mp4"></div>
<button onclick="Harmonica(this,'myVideo')" type="button"> Video 2</button>
<video height="auto" width="500"id="myVideo" controls autoplay loop class="myvideo">
<source id="mp4_src" src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
</video>
</body>
<script>
var vid = document.getElementById("myVideo");
var statusElement = document.getElementById("status");
var currentlyPlaying = 1;
var currentlPlayingTime;
var src1 = document.getElementsByClassName("video1")[0].id;
var src2 = document.getElementsByClassName("video2")[0].id;
function Harmonica(btn,myVideo) {
currentlPlayingTime = vid.currentTime;
if (currentlyPlaying === 1) {
vid.src = src2;
currentlyPlaying = 2;
btn.innerHTML = "Video 1";
} else {
vid.src = src1;
currentlyPlaying = 1;
btn.innerHTML = "Video 2";
}
vid.load();
vid.addEventListener('canplay', function () {
vid.currentTime = currentlPlayingTime;
}, false);
}
</script>
</html>

How do I stop one audio track when another one starts? (with only a text link)

I was trying to play a list of audio files on the same web page with only a text link as play button, and I found the following solution, which works really perfect for me:
(thanks #linstantnoodles for this script!)
<audio id="song1" preload='auto'>
<source src='song1.mp3' type='audio/mp3' />
</audio>
<audio id="song2" preload='auto'>
<source src='song2.mp3' type='audio/mp3' />
</audio>
Listen
Listen
<script type="text/javascript">
// List of audio/control pairs
var playlist = [{
"audio": document.getElementById('song1'),
"control": document.getElementById('song1-control')
}, {
"audio": document.getElementById('song2'),
"control": document.getElementById('song2-control')
}];
for (var i = 0; i < playlist.length; i++) {
var obj = playlist[i];
var audio = obj.audio;
var control = obj.control;
// returns a closure
var listener = function (control, audio) {
return function () {
var pause = control.innerHTML === 'Pause';
control.innerHTML = pause ? 'Listen' : 'Pause';
// Update the Audio
var method = pause ? 'pause' : 'play';
audio[method]();
// Prevent Default Action
return false;
}
};
control.addEventListener("click", listener(control, audio));
}
</script>
My only problem with this code is, that if one song is playing, and I start a second one, both are playing at the same time. I've tried many ways to get this problem fixed, but none of them did work - how do I need to adapt it, so that the first one pauses or stops when a second one starts? Thanks!
You can do something like this. When a new audio is started, loop through the playlist array to find all the audio elements that are not the one that just got started and stop them.
Here is an example:
....
var method = pause ? 'pause' : 'play';
audio[method]();
if(!pause){
playlist.forEach(function(pl){
if(pl.audio !== audio){
pl.audio.pause();
pl.audio.currentTime = 0;
pl.control.innerHTML = 'Listen';
}
});
}
....

Web: How to play audio files one after the other without a delay ?

I have urls of several audio files like this:
example.net/{num}.mp3
And I would like to play them one after the other without a delay between them.
I tried having two audio elements with preload=true and switching between them, but I still have a delay.
Any ideas ?
I'd like to see the actual code of what you have so far, because I'm not 100% sure what "switching between them" means, but I wrote the following example which starts the next file playing before the first one finishes. You specify a set amount of "overlap", and it starts playing the next file JSFiddle: http://jsfiddle.net/76xqhupw/4/
const OVERLAP_TIME = 1.0; //seconds
const song1 = document.getElementById('audio1');
const song2 = document.getElementById('audio2');
song1.addEventListener("timeupdate", function() {
if (song1.duration - song1.currentTime <= OVERLAP_TIME) {
song2.play();
}
});
song1.play();
This is just relevant to playing the next audio element instantly, since you said you already had two audio elements, but if I'm missing something let me know.
<html>
<head>
<title>Subway Maps</title>
<link rel="stylesheet" type="text/css" href="main.css" />
</head>
<body onload="onload();">
<video id="idle_video" width="1280" height="720" onended="onVideoEnded();"></video>
<script>
var video_list = ["Skydiving Video - Hotel Room Reservation while in FreeFall - Hotels.com.mp4",
"Experience Conrad Hotels & Resorts.mp4",
"Mount Airy Casino Resort- Summer TV Ad 2.mp4"
];
var video_index = 0;
var video_player = null;
function onload(){
console.log("body loaded");
video_player = document.getElementById("idle_video");
video_player.setAttribute("src", video_list[video_index]);
video_player.play();
}
function onVideoEnded(){
console.log("video ended");
if(video_index < video_list.length - 1){
video_index++;
}
else{
video_index = 0;
}
video_player.setAttribute("src", video_list[video_index]);
video_player.play();
}
</script>
</body>
for refrence how to display multiple videos one by one dynamically in loop using HTML5 and javascript
You can use ended event, Array.prototype.shift() to set src of element to next item within array, if array .length is greater than 0, call .load(), .play()
var url = "example.net/"
var type = ".mp3";
var n = [0,1,2,3,4,5];
var audio = document.querySelector("audio");
audio.onended = function() {
if (n.length) {
this.src = url + n.shift() + type;
this.load();
this.play();
}
}
audio.src = url + n[0] + type;
audio.load();
audio.play();

Infinite loop with random playlist

I have numerous MP3 files in a folder.
When I enter a page, I want a song from that playlist to play. After this song is over, I want a new one to play (not the same one) and so on.
<script type="text/javascript">
var song = ["../audio/1.mp3" , "../audio/2.mp3", "../audio/3.mp3", "../audio/4.mp3", "../audio/5.mp3" ];
var soundFile = song[Math.floor(Math.random()*song.length)];
document.write("<embed id='sound' src='" + soundFile + "' loop='true' type='audio/mpeg' controller='false' height='0' width='0'>");
</script>
What's wrong, because it always plays the same song.
Use an already defined embedded element and set the src attribute.
<embed id='sound' loop='true' type='audio/mpeg' controller='false' height='0' width='0'>
<script type="text/javascript">
var songs = ["../audio/1.mp3" , "../audio/2.mp3", "../audio/3.mp3", "../audio/4.mp3", "../audio/5.mp3" ];
var remainingSongs = songs;
var el = document.getElementById("sound");
var pickSong = function(){
// No songs left?
if(!remainingSongs.length) {
remainingSongs = songs;
}
// Pick song
var index = Math.floor(Math.random() * (remainingSongs.length - 1));
var soundFile = remainingSongs[index];
// Remove song from array
remainingSongs.splice(index, 1);
el.setAttribute("src", soundFile);
}
pickSong();
el.addEventListener("ended", pickSong, false);
</script>
You have an off-by-one error. I think it should be:
var soundFile = song[(Math.floor((Math.random())*(song.length-1)))];
But otherwise this should work. Could be a combination of the erroneous code and weird browser caching?
Also, check the web server you are using to serve the files and clear its cache.
Plus make sure your audio files are actually different.
Also, random chance may be tricking you. Give it a few goes.
This works for me in Chrome Canary on OSX:
<!DOCTYPE html>
<html>
<head>
<script>
var song = ['./foo.m4a', 'bar.m4a', 'bam.m4a'];
var soundFile = song[(Math.floor((Math.random())*(song.length-1)))];
document.write('<embed id="sound" src="' + soundFile + '" loop="true" type="audio/mpeg" controller="false" height="0" width="0">');
</script>
</head>
<body></body>
</html>
The problem is the loop attribute for the embed element doesn't know about your array of audio sources. It's just going to loop over the same source file.
Luckily, there is a pretty easy solution. The following will create an Audio element, with the Audio constructor, and continue to set a "random" audio source from the song array when the previous is done playing. We can do this by listening for the ended event.
<script type="text/javascript">
var song = ["../audio/1.mp3" , "../audio/2.mp3", "../audio/3.mp3", "../audio/4.mp3", "../audio/5.mp3" ];
var audio = new Audio();
var setSound = function() {
var soundFile = escape(song[Math.floor(Math.random()*song.length)]);
audio.setAttribute('src', soundFile);
audio.play();
};
// set initial source
setSound();
// set a new source, when current sound is done playing
audio.addEventListener('ended', setSound, false);
</script>

Get cue in HTML5 track element

In testing out the HTML5 track element, the cue comes up null. The TextTrackList and track element appear to load. Also, I am aware that VTT files aren't accessible locally, and I'm testing on a server. Can anyone help out? Thanks in advance.
This is my Javascript:
var audioElement = document.querySelector("audio");
var textTracks = audioElement.textTracks;
var textTrack = textTracks[0];
var ques = textTrack.cues;
var que = ques[0];
console.log(que);
Here's the HTML:
<audio src="Audio Files/Q_firefox.ogg" controls>
<track src="cues.vtt"></track>
</audio>
The cue value changes as the track plays so you need to listen for the value to change and run your function each time the text changes. Try this example based on your question:
var audioElement = document.querySelector("audio");
var textTrack = audioElement.textTracks[0];
// When cue value changes run your code
textTrack.oncuechange = function(e) {
var cue = this.activeCues[0];
if(cue){
console.log(cue.text);
}
}
<audio src="http://html5-demos.appspot.com/static/video/track/Google_Developer_Stories.webm" controls>
<track src="http://html5-demos.appspot.com/static/video/track/video-subtitles-en.vtt" default>
</audio>
Also note no need to close HTML track tag.

Categories

Resources