HTML5 Audio stop function - html

I am playing a small audio clip on click of each link in my navigation
HTML Code:
<audio tabindex="0" id="beep-one" controls preload="auto" >
<source src="audio/Output 1-2.mp3">
<source src="audio/Output 1-2.ogg">
</audio>
JS code:
$('#links a').click(function(e) {
e.preventDefault();
var beepOne = $("#beep-one")[0];
beepOne.play();
});
It's working fine so far.
Issue is when a sound clip is already running and i click on any link nothing happens.
I tried to stop the already playing sound on click of link, but there is no direct event for that in HTML5's Audio API
I tried following code but it's not working
$.each($('audio'), function () {
$(this).stop();
});
Any suggestions please?

Instead of stop() you could try with:
sound.pause();
sound.currentTime = 0;
This should have the desired effect.

first you have to set an id for your audio element
in your js :
var ply = document.getElementById('player');
var oldSrc = ply.src;// just to remember the old source
ply.src = "";// to stop the player you have to replace the source with nothing

I was having same issue. A stop should stop the stream and onplay go to live if it is a radio. All solutions I saw had a disadvantage:
player.currentTime = 0 keeps downloading the stream.
player.src = '' raise error event
My solution:
var player = document.getElementById('radio');
player.pause();
player.src = player.src;
And the HTML
<audio src="http://radio-stream" id="radio" class="hidden" preload="none"></audio>

Here is my way of doing stop() method:
Somewhere in code:
audioCh1: document.createElement("audio");
and then in stop():
this.audioCh1.pause()
this.audioCh1.src = 'data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAVFYAAFRWAAABAAgAZGF0YQAAAAA=';
In this way we don`t produce additional request, the old one is cancelled and our audio element is in clean state (tested in Chrome and FF) :>

This method works:
audio.pause();
audio.currentTime = 0;
But if you don't want to have to write these two lines of code every time you stop an audio you could do one of two things. The second I think is the more appropriate one and I'm not sure why the "gods of javascript standards" have not made this standard.
First method: create a function and pass the audio
function stopAudio(audio) {
audio.pause();
audio.currentTime = 0;
}
//then using it:
stopAudio(audio);
Second method (favoured): extend the Audio class:
Audio.prototype.stop = function() {
this.pause();
this.currentTime = 0;
};
I have this in a javascript file I called "AudioPlus.js" which I include in my html before any script that will be dealing with audio.
Then you can call the stop function on audio objects:
audio.stop();
FINALLY CHROME ISSUE WITH "canplaythrough":
I have not tested this in all browsers but this is a problem I came across in Chrome. If you try to set currentTime on an audio that has a "canplaythrough" event listener attached to it then you will trigger that event again which can lead to undesirable results.
So the solution, similar to all cases when you have attached an event listener that you really want to make sure it is not triggered again, is to remove the event listener after the first call. Something like this:
//note using jquery to attach the event. You can use plain javascript as well of course.
$(audio).on("canplaythrough", function() {
$(this).off("canplaythrough");
// rest of the code ...
});
BONUS:
Note that you can add even more custom methods to the Audio class (or any native javascript class for that matter).
For example if you wanted a "restart" method that restarted the audio it could look something like:
Audio.prototype.restart= function() {
this.pause();
this.currentTime = 0;
this.play();
};

It doesn't work sometimes in chrome,
sound.pause();
sound.currentTime = 0;
just change like that,
sound.currentTime = 0;
sound.pause();

From my own javascript function to toggle Play/Pause - since I'm handling a radio stream, I wanted it to clear the buffer so that the listener does not end up coming out of sync with the radio station.
function playStream() {
var player = document.getElementById('player');
(player.paused == true) ? toggle(0) : toggle(1);
}
function toggle(state) {
var player = document.getElementById('player');
var link = document.getElementById('radio-link');
var src = "http://192.81.248.91:8159/;";
switch(state) {
case 0:
player.src = src;
player.load();
player.play();
link.innerHTML = 'Pause';
player_state = 1;
break;
case 1:
player.pause();
player.currentTime = 0;
player.src = '';
link.innerHTML = 'Play';
player_state = 0;
break;
}
}
Turns out, just clearing the currentTime doesn't cut it under Chrome, needed to clear the source too and load it back in. Hope this helps.

As a side note and because I was recently using the stop method provided in the accepted answer, according to this link:
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events
by setting currentTime manually one may fire the 'canplaythrough' event on the audio element. In the link it mentions Firefox, but I encountered this event firing after setting currentTime manually on Chrome. So if you have behavior attached to this event you might end up in an audio loop.

shamangeorge wrote:
by setting currentTime manually one may fire the 'canplaythrough' event on the audio element.
This is indeed what will happen, and pausing will also trigger the pause event, both of which make this technique unsuitable for use as a "stop" method. Moreover, setting the src as suggested by zaki will make the player try to load the current page's URL as a media file (and fail) if autoplay is enabled - setting src to null is not allowed; it will always be treated as a URL. Short of destroying the player object there seems to be no good way of providing a "stop" method, so I would suggest just dropping the dedicated stop button and providing pause and skip back buttons instead - a stop button wouldn't really add any functionality.

This approach is "brute force", but it works assuming using jQuery is "allowed". Surround your "player" <audio></audio> tags with a div (here with an id of "plHolder").
<div id="plHolder">
<audio controls id="player">
...
</audio>
<div>
Then this javascript should work:
function stopAudio() {
var savePlayer = $('#plHolder').html(); // Save player code
$('#player').remove(); // Remove player from DOM
$('#FlHolder').html(savePlayer); // Restore it
}

I was looking for something similar due to making an application that could be used to layer sounds with each other for focus. What I ended up doing was - when selecting a sound, create the audio element with Javascript:
const audio = document.createElement('audio') as HTMLAudioElement;
audio.src = getSoundURL(clickedTrackId);
audio.id = `${clickedTrackId}-audio`;
console.log(audio.id);
audio.volume = 20/100;
audio.load();
audio.play();
Then, append child to document to actually surface the audio element
document.body.appendChild(audio);
Finally, when unselecting audio, you can stop and remove the audio element altogether - this will also stop streaming.
const audio = document.getElementById(`${clickedTrackId}-audio`) as HTMLAudioElement;
audio.pause();
audio.remove();

If you have several audio players on your site and you like to pause all of them:
$('audio').each( function() {
$(this)[0].pause();
});

I believe it would be good to check if the audio is playing state and reset the currentTime property.
if (sound.currentTime !== 0 && (sound.currentTime > 0 && sound.currentTime < sound.duration) {
sound.currentTime = 0;
}
sound.play();

for me that code working fine. (IE10+)
var Wmp = document.getElementById("MediaPlayer");
Wmp.controls.stop();
<object classid="clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6"
standby="Loading áudio..." style="width: 100%; height: 170px" id="MediaPlayer">...
Hope this help.

What I like to do is completely remove the control using Angular2 then it's reloaded when the next song has an audio path:
<audio id="audioplayer" *ngIf="song?.audio_path">
Then when I want to unload it in code I do this:
this.song = Object.assign({},this.song,{audio_path: null});
When the next song is assigned, the control gets completely recreated from scratch:
this.song = this.songOnDeck;

The simple way to get around this error is to catch the error.
audioElement.play() returns a promise, so the following code with a .catch() should suffice manage this issue:
function playSound(sound) {
sfx.pause();
sfx.currentTime = 0;
sfx.src = sound;
sfx.play().catch(e => e);
}
Note: You may want to replace the arrow function with an anonymous function for backward compatibility.

In IE 11 I used combined variant:
player.currentTime = 0;
player.pause();
player.currentTime = 0;
Only 2 times repeat prevents IE from continuing loading media stream after pause() and flooding a disk by that.

What's wrong with simply this?
audio.load()
As stated by the spec and on MDN, respectively:
Playback of any previously playing media resource for this element stops.
Calling load() aborts all ongoing operations involving this media element

Related

Mission : Create a connection with a list of videos and a canvas make them plays 1 by 1, without stops, no click function, ended AddEventListener

I would like to make a video playlist, (Source video is copied in a canvas to block controls,
options like download video), i made 2 Drag and Drop lists and i would like to connect 1 drag n Drop list to the canvas (that is also the video player box) then play the videos 1 by 1,
witout stops, no click function, function AddEventListener ended in the canvas box.
I worth for 2 videos, here is some parts of the code :
<script type="text/javascript">
// listener function changes src
function myNewSrc() {
var myVideo = document.getElementsByTagName('video')[0];
myVideo.src = "videos/80s_Mix_II-700.mp4";
myVideo.src = "videos/80s_Mix_II-700.webm";
myVideo.load();
myVideo.play();
}
// add a listener function to the ended event
function myAddListener() {
var myVideo = document.getElementsByTagName('video')[0];
myVideo.addEventListener('ended', myNewSrc, false);
}
</script>
<body onload="myAddListener()">
<div id="video_player_box">
<video id="video" autoplay autobuffer width="1" height="1" >
<source src="videos/milenio_6_minimix_700.mp4" type="video/mp4">
<source src="videos/milenio_6_minimix_700.webm" type="video/webm">
<source src="videos/milenio_6_minimix_700.ogg" type="video/ogg">
</video>
<div align="center">
<canvas id="myCanvas" width="1130" height="560">
Your browser does not support the HTML5 canvas tag.</canvas>
</div>
<script>
var v = document.getElementById("video");
var c = document.getElementById("myCanvas");
ctx = c.getContext('2d');
v.addEventListener('play', function() {
var i = window.setInterval(function()
{
ctx.drawImage(v, 5, 5, 1130, 560)
}, 20);
}, false);
v.addEventListener('pause', function() {
window.clearInterval(i);
}, false);
v.addEventListener('ended', function() {
clearInterval(i);
}, false);
</script>
</div>
<div id="cadre2" ondrop="drop(event)" ondragover="allowDrop(event)"> <p> Canal VIP </p>
<ol><li> <video src="videos/milenio_6_minimix_700.mp4" draggable="true"
ondragstart="drag(event)" id="drag1" width="288" height="188" alt="Video 1">
</video></li>
...
The idea is to say get the videos from #cadre2, play them, 1 by 1, in the canvas until the end and loop, make the same path.
I made my list Drag and drop to have the decision to modify online the video playlist, more flexible.
Hope to have some advises!! I'm not pro of Php and dynamic, i've started Javascript but
it takes time to be pro!
If you have some code, it will be really appreciated!! Thanks in advance!!!
In order to make a player that can play videos continously you need to implement some sort of double-buffering at load level (I'll demonstrate later).
But there are some issues in the code as it is -
myVideo.src = "videos/80s_Mix_II-700.mp4";
myVideo.src = "videos/80s_Mix_II-700.webm";
myVideo.load();
This will simply override the source property. And setting the source will automatically start loading the video.
The proper way to check for video support is using the method canPlayType like this:
/// which format can we play?
if (video.canPlayType("video/mp4").length > 0) {
video.src = urlToMP4;
} else if (video.canPlayType("video/webm").length > 0) {
video.src = urlToWEBM;
} else {
video.src = urlToOggOrSomeOtherSupportedFormat;
}
The problem though with canPlayType is that it returns maybe in Chrome and probably in Firefox. It returns an empty string if it cannot play the video type so we check if string contains anything to determine the possibility for this format to play.
You also need to implement an event listener for canplay which tells your app that the video was loaded and buffered successfully and can now be started using play (or starts if autoplay was set to true).
I would recommend a simple procedure like this:
Create an array of objects with the video URLs you want to play for the various formats
When first video is loaded (canplay) start loading the next video in the list when start playing the first
I would also recommend a re-factoring of the code to handle loading and playing.
For example, if we initialize an array to hold our custom video objects:
var list = [];
we can now add URLs like this:
function addVideo(urlMP4, url) {
list.push({
urlMP4: urlMP4,
url: url,
isReady: false
})
}
Then this function will let us add a MP4 and a link for WEBM or OGG:
addVideo('http://video1.mp4', 'http://video1.webm');
addVideo('http://video2.mp4', 'http://video2.webm');
addVideo('http://video3.mp4', 'http://video3.ogg');
...
Then we need to start a "chain-reaction" so to speak by using a double-buffered loading mechanism. The first time we need to trigger it manually:
getVideo(list[0], play);
function getVideo(vid, callback) {
/// which video is playing? (see demo for details)
var video = (isVideo1 === false ? video1 : video2),
me = this;
/// we need to know when video is ready
video.addEventListener('canplay', canPlay, false);;
/// call this when ready
function canPlay(e) {
/// remove event listener (in case setting new src does not trigger)
video.removeEventListener('canplay', canPlay, false);
/// update our object with useful data, for example:
vid.isReady = true;
/// if we provided a callback then call that with custom video object
if (typeof callback === 'function')
callback(vid);
}
/// check video format support (see demo for details)
if (video.canPlayType("video/mp4").length > 0) {
video.src = vid.urlMP4;
} else {
video.src = vid.url;
}
}
Our play function will manage which video is playing and what to play next:
function play(){
/// what video is currently not playing?
var video = (isVideo1 === false ? video1 : video2),
next = current; /// current is index for list, starts at 0
/// switch
isVideo1 = !isVideo1;
/// increment for next video to platy and start over if list ended
next++;
if (next > list.length - 1) next = 0;
/// only attempt next if there are more videos than 1 in list
if (list.length > 0) getVideo(list[next]);
/// start already loaded video (getVideo)
video.play();
isPlaying = true;
/// set current to next in list
current = next;
}
Here is an online demo
I made this demo just to demonstrate the double-buffered loading. Feel free to incorporate in your own project with pause, stop etc.
There is room to move things around in the code I provided here but it's as said just example of the principle. You also need to consider a scenario where next video takes longer to load then what current video playing takes to play (ie. current video ends before next has finished loading). This is not checked in this code.
In order to properly synchronize video frames with canvas you need to use requestAnimationFrame or you will get freezes from time to time.
In the demo the loop runs all the time. You can consider to implement a conditional to stop the loop. I just implemented a conditional for drawing when video list has started playing (rAF does not use much resources in it self and you may get problems synchronizing stop and start when you switch videos so I would personally leave it running as-is for this type of scenarios (continuous video play) and only stop it if there is an error occurring).

How can I get the size of the webcam image with getUserMedia?

I'm trying to find out what will be the size of the image I get from the webcam using getUserMedia.
Right now, in my Macbook, I have supposedly a 720p camera, but the image I'm getting is 640x480. I'm assuming this won't always be the case, though, and I'd like to be able to handle as many cameras as possible. (I care way more about aspect ratio than size itself, I just want to make sure pictures don't show up stretched)
Is it possible to do this?
Thank you!
Daniel
You should be able to use videoWidth and videoHeight attributes, like this:
// Check camera stream is playing by getting its width
video.addEventListener('playing', function() {
if (this.videoWidth === 0) {
console.error('videoWidth is 0. Camera not connected?');
}
}, false);
UPDATE: Actually, this works in Opera but doesn't seem to be supported in Chrome any more and hasn't been implemented in Firefox (at least not for video streams). It's in the HTML5 spec, though, so hopefully is on the roadmap for these browsers.
UPDATE 2: This does work, but the event to listen for is "playing" and not "play" (fixed in the code above). The "play" event is fired when the play() method is returned, whereas the "playing" event is fired when playback has actually started. Tested in Opera, Chrome and Firefox.
UPDATE 3: Firefox 18 seems to fire the "playing" event repeatedly, meaning the browser could grind to a halt if you're executing a lot of code within the listener. Better to remove the listener after it's fired, like so:
var videoWidth, videoHeight;
var getVideoSize = function() {
videoWidth = video.videoWidth;
videoHeight = video.videoHeight;
video.removeEventListener('playing', getVideoSize, false);
};
video.addEventListener('playing', getVideoSize, false);
Hooking into the playing event does not work in Firefox (at least in Firefox 26.0 on Ubuntu 12.04 LTS I use). The playing event fires once or twice after the video starts playing. videoWidth and videoHeight are either 0 or undefined when the playing event fires. A more reliable way to detect videoWidth and videoHeight is pausing and playing the video, that seems to work always. The code snippet below worked for me:
//Detect camera resolution using pause/play loop.
var retryCount = 0;
var retryLimit = 25;
var video = $('.video')[0]; //Using jquery to get the video element.
video.onplaying = function(e) {
var videoWidth = this.videoWidth;
var videoHeight = this.videoHeight;
if (!videoWidth || !videoHeight) {
if (retryCount < retryLimit) {
retryCount++;
window.setTimeout(function() {
video.pause();
video.play();
}, 100);
}
else {
video.onplaying = undefined; //Remove event handler.
console.log('Failed to detect camera resolution after ' + retryCount + ' retries. Giving up!');
}
}
else {
video.onplaying = undefined; //Remove event handler.
console.log('Detected camera resolution in ' + retryCount + ' retries.');
console.log('width:' + videoWidth + ', height:' + videoHeight);
}
};

AudioElement resume playback stutters for a second and stops

I'm trying to use html5 audio with Dart and Chrome, and I'm going the easy way of using AudioElement as much as possible. I want to be able to pause sound and resume it later. I have:
startSound() {
audioElement.src = "foo";
audioElement.load();
audioElement.play();
}
pause() {
this.time = audioElement.currentTime;
audioElement.pause();
}
unpause() {
audioElement.currentTime = this.time;
audioElement.play();
}
These are hooked up to event handlers, so when someone clicks the 'pause' button, playback stops. When they hit the 'resume' button, though, playback resumes for only about half a second before stopping again.
How do I get audio to resume properly?
There appears to be a timing issue in Chrome. You need to tell Chrome to play, then pause again, then play again, with a short delay between each.
A working version of the unpause method is:
unpause() {
var fn = () {
audioElement.currentTime = this.time;
audioElement.play();
};
fn();
window.setTimeout(() => audioElement.pause(), 25);
window.setTimeout(fn, 50);
}
I had a similar problem with Chrome. It stuttered before playing when I "resumed" the audio element, and I didn't have the same problem in Safari. It turned out, however, that Chrome was somehow not happy with my mp3 format. Adding an ogg version of the file to the sources in my tag solved the problem.

Play sound at certain playProgress or videoTime with greensock?

I'm using greensock LoaderMax to load video files and sound files. I've copied as much code as is available to me. A video (s9) is playing and at a certain percentage through the video, I need to play another sound.
if(s9.playProgress > .1) // This is what I can't get to work
{
s12_sound.playSound(); //This sound won't play at .1 playProgress
}
s9.content.visible = true;
s9.playVideo();
stop();
s9.addEventListener(VideoLoader.VIDEO_COMPLETE, play_s9_loop); //This plays a video once s9 is done.
function play_s9_loop(event:Event):void
{
s9.content.visible = false;
s9_loop.content.visible = true;
s9_loop.playVideo();
}
I'm guessing you just can't do an if() on playProgress? Furthermore, I suck at AS3.
You should be able to just listen for the INIT event on the video (which typically means it has loaded enough to determine the duration of the video) and then add an AS cue point.
//...after you create your VideoLoader...
myVideoLoader.addEventListener(LoaderEvent.INIT, initHandler);
myVideoLoader.load();
function initHandler(event:LoaderEvent):void {
myVideoLoader.addASCuePoint( myVideoLoader.duration * 0.1, "myLabel" );
myVideoLoader.addEventListener(VideoLoader.VIDEO_CUE_POINT, cuePointHandler);
}
function cuePointHandler(event:LoaderEvent):void {
trace("Hit the cue point " + event.data.name);
s12_sound.playSound();
}
Also make sure that you preload that s12_sound so that it's ready to play when you need it. Otherwise, you can call playSound() all you want and it ain't gonna happen :)
I haven't used this class before but after reading the docs it looks like you can do something like this:
http://www.greensock.com/as/docs/tween/com/greensock/loading/VideoLoader.html
var mid:Number = s9_loop.duration/2; //get the midpoint using the duration property
s9_loop.addASCuePoint(mid, "middle") //using addASCubePoint to add a cuepoint to the midpoint of the video
s9_loop.addEventListener(VideoLoader.VIDEO_CUE_POINT, handleMidpoint); //listen for the cuepoint
Inside the handler function
protected function handleMidpoint(e:Event):void{
//play your sound
}

How to do something after video finishes?

I have a 15 second video that's not embedded (it's sourced from an url). How can I get it to play the next frame when then video is finished?
If you are using the FLVPlayback component, you can do it like this:
// for clarification
var video:FLVPlayback = myVideoInstance;
video.source = "http://example.com/myvideo.flv";
video.autoPlay = true;
video.addEventListener(VideoEvent.COMPLETE, function(e:VideoEvent) {
// video has finished
});
See VideoEvent.COMPLETE which is dispatched when a video has finished playing.
video.addEventListener(VideoEvent.COMPLETE, _doNext);
function _doNext(e:VideoEvent):void
{
video.removeEventListener(VideoEvent.COMPLETE, _doNext);
trace("video done, what's next?");
}