How to pause/stop playing audio and replace with new audio file - javascript

So when the user clicks a button an audio file plays from an array of audio files(around 2 sec clip), which works fine. However, if the user repeatedly clicks the button, the audio files start to play over each other. Ideally, I would like to stop/pause the previous audio file and then play the new audio file. This is what I've tried to avail:
$scope.sounder=function(){
$scope.rs=$scope.diff[$scope.workout_index].audiorep;
$scope.ms=$scope.diff[$scope.workout_index].audiomove;
//var movesound = new Audio ($scope.ms);
//ar repsound = new Audio ($scope.rs);
var movesound = new Media($rootScope.getMediaURL($scope.ms));
var repsound = new Media($rootScope.getMediaURL($scope.rs));
if($scope.muter==0){
movesound.pause();//DOES NOT WORK
movesound.stop();//STOPS ALL AUDIO FROM PLAYING, SO NOTHING PLAYS
$timeout(function() {
movesound.play();
}, 1000);
$timeout(function() {
repsound.play();
}, 3000);
}
if($scope.muter==1){
console.log("Rachel has been muted");
return;
}
}

You can achieve the functionalities with JavaScript in Cordova unless you specifically need AngularJS in your app.
<audio controls id="myAudio">
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the HTML5 audio tag.
</audio>
Now using script to add functionalities -
<script>
var aud= document.getElementById("myAudio");
function playAud() {
aud.play();
}
function pauseAud() {
aud.pause();
}
function myFunction() {
isSupp = aud.canPlayType("audio/mp3");
if (isSupp == "") {
aud.src = "audio.ogg";
} else {
aud.src = "audio.mp3";
}
aud.load();
}
</script>
See other answers of this question on for changing source of audio with JavaScript.
Refer w3schools HTML Audio Video DOM reference Page for further attributes and functions.

Related

Multiple HTML5 videos audio captions not working correctly

I am adding multiple HTML5 videos onto a webpage.
The code I am replicating is from this recommended accessible approach. http://jspro.brothercake.com/audio-descriptions/ The video plays fine, and audio captions work, but when I add a new video to the same page the second video does not play the audio captions at all. Does anyone have suggestions on how I can fix this issue?
<video id="video" preload="auto" controls="controls"
width="640" height="360" poster="./media/HorribleHistories.jpg">
<source src="./media/HorribleHistories.mp4" type="video/mp4" />
<source src="./media/HorribleHistories.webm" type="video/webm" />
</video>
<audio id="audio" preload="auto">
<source src="./media/HorribleHistories.mp3" type="audio/mp3" />
<source src="./media/HorribleHistories.ogg" type="audio/ogg" />
</audio>
<script type="text/javascript">
(function()
{
//get references to the video and audio elements
var video = document.getElementById('video');
var audio = document.getElementById('audio');
//if media controllers are supported,
//create a controller instance for the video and audio
if(typeof(window.MediaController) === 'function')
{
var controller = new MediaController();
audio.controller = controller;
video.controller = controller;
}
//else create a null controller reference for comparison
else
{
controller = null;
}
//reduce the video volume slightly to emphasise the audio
audio.volume = 1;
video.volume = 0.8;
//when the video plays
video.addEventListener('play', function()
{
//if we have audio but no controller
//and the audio is paused, play that too
if(!controller && audio.paused)
{
audio.play();
}
}, false);
//when the video pauses
video.addEventListener('pause', function()
{
//if we have audio but no controller
//and the audio isn't paused, pause that too
if(!controller && !audio.paused)
{
audio.pause();
}
}, false);
//when the video ends
video.addEventListener('ended', function()
{
//if we have a controller, pause that
if(controller)
{
controller.pause();
}
//otherwise pause the video and audio separately
else
{
video.pause();
audio.pause();
}
}, false);
//when the video time is updated
video.addEventListener('timeupdate', function()
{
//if we have audio but no controller,
//and the audio has sufficiently loaded
if(!controller && audio.readyState >= 4)
{
//if the audio and video times are different,
//update the audio time to keep it in sync
if(Math.ceil(audio.currentTime) != Math.ceil(video.currentTime))
{
audio.currentTime = video.currentTime;
}
}
}, false);
})();
</script>
So your problem is to do with how you are grabbing the elements in the first place.
var video = document.getElementById('video');
var audio = document.getElementById('audio');
What you are doing is grabbing a single item on the page with the ID of "video" (same for "audio").
IDs have to be unique, so what you want to do is use classes instead.
<video class="video" preload="auto" controls="controls"
width="640" height="360" poster="./media/HorribleHistories.jpg">
See I changed the ID to a class.
Now any element with the class "video" can be used in our code.
However we do need to modify our code a bit as now we have multiple items to bind to.
please note the below is to give you an idea of how you loop items etc. You would need to rewrite your code to move each of the steps into functions etc. as your original code is not designed to work with multiple items
(function()
{
//get references to every single video and audio element
var videos = document.querySelectorAll('.video');
var audios = document.querySelectorAll('.audio');
// loop through all videos adding logic etc.
for(x = 0; x < videos.length; x++){
// grab a single video from our list to make our code neater
var video = videos[x];
if(typeof(window.MediaController) === 'function')
{
var controller = new MediaController();
video.controller = controller;
} else {
controller = null;
}
video.volume = 0.8;
//...etc.
}
})();
Quick Tip:
I would wrap your <video> and <audio> elements that are related in a <div> with a class (e.g. class="video-audio-wrapper").
This way you can change your CSS selector to something like:
var videoContainers = document.querySelectorAll('.video-audio-wrapper');
Then loop through them instead and check if they have a video and / or audio element
for(x = 0; x < videoContainers.length; x++){
var thisVideoContainer = videoContainers[x];
//query this container only - we can use `querySelector` as there should only be one video per container and that returns a single item / the first item it finds.
var video = thisVideoContainer.querySelector('video');
var audio = thisVideoContainer.querySelector('audio');
//now we can check if an element exists
if(video.length == 1){
//apply video logic
}
if(audio.length == 1){
//apply audio logic
}
// alternatively we can check both exist if we have to have both
if(video.length != 1 || audio.length != 1){
// we either have one or both missing.
// apply any logic for when a video / audio element is missing
//using "return" we can exit the function early, meaning all code after this point is not run.
return false;
}
///The beauty of this approach is you could then just use your original code!
}
Doing it this way you could recycle most of your code.
Thank you for your suggestions in changing the ID's into classes and adding the video wrapper <div> to the video container. That all makes sense in grouping each video on 1 page. I updated the the following code, but the audio captions won't play at all. The video plays and pauses fine, and the volume works. I am also not getting any syntax errors in the browser console. Here's what I got for my HTML and JS. I appreciate your help/feedback.
<div class="video-container-wrapper">
<div class="video-container">
<video class="video" preload="auto" controls="controls" width="640" height="360" poster="img/red-zone-thumb.png">
<source src="https://player.vimeo.com/external/395077086.hd.mp4?s=1514637c1ac308a950fafc00ad46c0a113c6e8be&profile_id=175" type="video/mp4">
<track kind="captions" label="English captions" src="captions/redzone-script.vtt" srclang="en" default="">
</video>
<audio class="audio" preload="auto">
<source src="captions/redzone-message.mp3" type="audio/mp3">
</audio>
</div>
</div>
Javascript:
var videoContainers = document.querySelectorAll('.video-container-wrapper');
for (x = 0; x < videoContainers.length; x++) {
var thisVideoContainer = videoContainers[x];
//query this container only - we can use `querySelector` as there should only be one video per container and that returns a single item / the first item it finds.
var video = thisVideoContainer.querySelector('video');
var audio = thisVideoContainer.querySelector('audio');
//now we can check if an element exists
if (video.length == 1) {
//apply video logic
//reduce the video volume slightly to emphasise the audio
video.volume = 0.8;
//when the video ends
video.addEventListener('ended', function () {
video.pause();
}, false);
}
if (audio.length == 1) {
//apply audio logic
audio.volume = 1;
//when the video plays
video.addEventListener('play', function () {
if (audio.paused) {
audio.play();
}
}, false);
// when the video ends
video.addEventListener('ended', function () {
audio.pause();
}, false);
//when the video time is updated
video.addEventListener('timeupdate', function () {
if (audio.readyState >= 4) {
//if the audio and video times are different,
//update the audio time to keep it in sync
if (Math.ceil(audio.currentTime) != Math.ceil(video.currentTime)) {
audio.currentTime = video.currentTime;
}
}
}, false);
}
}

How do I make a random video play on pageload?

I'm trying to make a random video player in html/js.
It is supposed to play a different video on pageload and as soon as one video is over, it should play another one.
HTML
<video width="320" height="240" autoplay>
<source src="abcdefg.com/example1.mp4" type="video/mp4">
<source src="abcdefg.com/example2.mp4" type="video/mp4">
</video>
JS
<script>
var videos = [
[{type:'mp4', 'src':'abcdefg.com/example1.mp4'}],
[{type:'mp4', 'src':'abcdefg.com/example2.mp4'}],
];
$(function() {
var number = Math.floor(Math.random()*videos.length);
$(this).find('source').each(function(index){
videoSrc = videos[number][index].src;
$(this).attr('src', videoSrc);
$('video').load();
$('video').play();
});
});
</script>
However, my current code plays the same video every page reload and as soon as it's over, nothing happens.
How do I need to optimize my code so it automatically plays a different video on every pageload + when the previous video is over?
Try this,I have added an event listener to video end property and called the newvideo() function ,so that every time the video finishes a new random video is loaded from array.I could'nt find more video urls ,you can test and let me know if it works for you.
$(document).ready(function(){
var videos = [
[{type:'mp4', 'src':'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4'}],
[{type:'mp4', 'src':'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4'}],
[{type:'mp4', 'src':'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4'}]
];
// selecting random item from array,you can make your own
var randomitem = videos[Math.floor(Math.random()*videos.length)];
// This function adds a new video source (dynamic) in the video html tag
function videoadd(element, src, type) {
var source = document.createElement('source');
source.src = src;
source.type = type;
element.appendChild(source);
}
// this function fires the video for particular video tag
function newvideo(src)
{
var vid = document.getElementById("myVideo");
videoadd(vid,src ,'video/ogg');
vid.autoplay = true;
vid.load();
//vid.play();
}
// function call
newvideo(randomitem[0].src)
// Added an event listener so that everytime the video finishes ,a new video is loaded from array
document.getElementById('myVideo').addEventListener('ended',handler,false);
function handler(e)
{
newvideo(randomitem[0].src)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<video width="320" height="240" autoplay id="myVideo">
</video>

check when video starts playing after populating src

I use the following code to check if the user is on desktop or mobile, if on desktop the src="" attribute of the video sources is populated. All fine. After populating the src attribute, I want to check the video has loaded before displaying it. Is there a way to do this?
Thanks!
JS
//video
if($.browser.mobile)
{
console.log("is mobile")
// it is mobile browser
}
else
{
console.log("is desktop")
// no mobile browser
var sources = document.querySelectorAll('video#patient-video source');
// Define the video object this source is contained inside
var video = document.querySelector('video#patient-video');
for(var i = 0; i<sources.length;i++) {
sources[i].setAttribute('src', sources[i].getAttribute('data-src'));
}
// If for some reason we do want to load the video after, for desktop as opposed to mobile (I'd imagine), use videojs API to load
video.load();
video.muted= "muted";
$(".main-area--cris-pro").addClass("loaded")
}
To check if it's a mobile browser, I use the plugin:
detectmobilebrowser.js
My HTML is as follows:
<video id="patient-video" width="100%" preload="none" poster="../../assets/img/patient-home-1600.jpg" autoplay loop>
<source data-src="../../assets/video/patient-home-video-comp.mp4" src="" type="video/mp4">
<source data-src="../../assets/video/patient-home-video-comp.webm" src="" type="video/webm">
<source data-src="../../assets/video/patient-home-video-comp.ogv" src="" type="video/ogg">
</video>
Use canplaythrough event.
The canplaythrough event is fired when the user agent can play the media, and estimates that enough data has been loaded to play the media up to its end without having to stop for further buffering of content.
var sources = document.querySelectorAll('video#patient-video source');
var video = document.querySelector('video#patient-video');
for (var i = 0; i < sources.length; i++) {
sources[i].setAttribute('src', sources[i].getAttribute('data-src'));
}
video.muted = true;//Set boolean value
video.addEventListener('canplaythrough', function() {
alert('Video Loaded!');
video.muted = false;
$(".main-area--cris-pro").addClass("loaded");
});

playing 2 or more .wav files one after another in java script

basically i want to play captcha digits. i have 1.wav, 2.wav etc.
i will send captcha digits to a function will seperate digits in the function and for each digit want to play corresponding .wav file.
Just for simple example, if i want to play 1.way, 2.way and 3.way, i am using :
function PlayCaptcha()
{
document.getElementById('audiotag1').play();
document.getElementById('audiotag2').play();
document.getElementById('audiotag3').play();
}
and
<audio id="audiotag1" src="sounds/1.wav" preload="auto"></audio>
<audio id="audiotag2" src="sounds/2.wav" preload="auto"></audio>
<audio id="audiotag3" src="sounds/3.wav" preload="auto"></audio>
PROBLEM is that it plays all file at very high speed. and only 3.wav playing can be listened.
i wish to have some gap after 1.wav is played then 2.wav is played then again some time gap and then 3.wav should be played.
Any solution please?
Use onended event of Audio, Alert that the audio has ended
Try this:
function PlayCaptcha() {
var audiotag1 = document.getElementById('audiotag1');
var audiotag2 = document.getElementById('audiotag2');
var audiotag3 = document.getElementById('audiotag3');
audiotag1.play();
audiotag1.onended = function() {
audiotag2.play();
};
audiotag2.onended = function() {
audiotag3.play();
};
audiotag3.onended = function() {
alert('Ended!');
};
}

Start playing HTML5 Video only after the complete video is buffered

Is there a way I can start playing my HTML5 MP4 video only after the entire video is buffered (100%). When it is in the process of buffering, I should display the Loading screen. Please help. This code should work in both Firefox and IE11.
Hyperlink Titles Example :
- Play Video1: Fav Foods - Play Video1: Fav Veg - Play Video2: Fav Animal
And here is the code I have when I click on the hyperlink and also the Video tags. I load the video dynamically from the database. The attribute 'pos' tells the time in seconds where the player has to seek playing.
<video id="VideoContainer" controls="controls" style="width:500px;height:320px" preload="auto">
<source id="VideoData" src=#Model.IntroVideoPath type="video/mp4" />
Your browser does not support the video tag.
<a onclick="navVideo('#items.FileName','#items.StartSec');">#items.DisplayText</a>
function navVideo(fileName, pos) {
//Get Player and the source
var player = document.getElementById('VideoContainer');
var mp4Vid = document.getElementById('VideoData');
var mp4CurVid = $(mp4Vid).attr('src');
//Reload the player only if the file name changes
if (mp4CurVid != fileName) {
$(mp4Vid).attr('src', fileName);
player.load();
player.play();
if (pos != 0) {
setTimeout(function () {
player.currentTime = pos;
player.play();
}, 1000);
}
}
else {
player.pause();
player.currentTime = pos;
player.play();
}
The problem was with the encoding technique for that MP4 file. I encoded with different settings (random settings options for Mp4) and finally got that to work without buffer.
You could use the this http://videojs.com/ to get that to work.

Categories

Resources