HTML audio Element how to replay? - javascript

I setup a HTML5 page, that include a node.
The page will to playing a music(mp3 format),but it just play sound to end, and I use javascript to control audio element,even so,I can't replay it and only STOP.
Does HTML5 audio Element support REPLAY? And how to?

please read this
http://www.position-absolute.com/articles/introduction-to-the-html5-audio-tag-javascript-manipulation/
and for replay event
you can set option, on replay click
audioElement.currentTime=0;
audioElement.play();

The suggestions above did not worked for me or where not applicable. I needed to replay sound when my code needed to do it.
The following code worked (at least chrome):
audioElement.setAttribute('src', audioSrc);
audioElement.play();
in other words, setting the src attribute again, then play() did the job

If the server hosting the video does not support seeking on client (HTTP RangeRequest), the command
audioElement.currentTime=0;
from #JapanPro's answer is silently ignored in Chromium. This behavior is filled as crbug #121765.
There is a handy guide on MDN how to configure your server to play nice. But if you cannot, I had success with doing
audioElement.load();
which unsurprisingly reloads the audio source and seeks to the start as a side effect. Not nice, but it is quite intuitive and it works.
source: http://www.whatwg.org/specs/web-apps/current-work/#loading-the-media-resource

Use:
audio.pause() // important!!!
audio.currentTime = 0
audio.play()

The html5 audio element has a loop attribute set it to loop=loop
http://www.w3schools.com/html5/html5_audio.asp

don't use node.load() this is way too slow for slow devices.
To stop, you should just use:
node.currentTime = 0
To replay you can do:
node.currentTime = 0
node.play()

You can try this:
<audio id="audiotag1" src="audio/flute_c_long_01.wav" preload="auto"></audio>
Play 5-sec sound on single channel
<script type="text/javascript">
function play_single_sound() {
document.getElementById('audiotag1').play();
}
</script>
Ref: http://www.storiesinflight.com/html5/audio.html

In HTML5 you can just set audioElement.loop='true';

Related

javascript not executed with setTimeout but does with button click event

I am trying to view a video stream from an IP camera in a web page, when the stream can be played I want it to start automatically. Trying to do that with a timer, try to play and if that fails, try again.
The timer (timeout) doesn't seem to do that, however if I execute the script using a button, it does. What am I missing?
see the code below.
thanks,
Ron
PS: I commented out the setTimeout functions, to make the button work.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function playVid() {
var videoElem = document.getElementById("IPcamerastream");
var playPromise = videoElem.play();
// In browsers that don’t yet support this functionality playPromise won’t be defined.
if (playPromise !== undefined) {
playPromise.then(function() {
// Automatic playback started!
videoElem.controls = true;
}).catch(function(error) {
// Automatic playback failed.
// setTimeout(playVid, 1000);
});
}
}
//setTimeout(playVid, 1000);
</script>
<button onclick="playVid()" type="button">Play Video</button><BR>
<video id="IPcamerastream" src="http://192.168.2.8:8080" width="960" height="540"></video>
</body>
</html>
Look into the features of the video html5 tag:(https://www.w3schools.com/tags/tag_video.asp)
one of the optional attributes is autoplay (Specifies that the video will start playing as soon as it is ready) so there is no need to set timeout.
<video id="IPcamerastream" src="http://192.168.2.8:8080" width="960" height="540" autoplay></video>
Move your script below the video element, and you should not need the timeout at all, because the element will already be initialized when the script is executed. So document.getElementById should resolve the element right away.
Using timers will introduce race conditions. If anything, you should add a listener to the DOMContentLoaded event.
Welcome Ron,
This is a well formatted question, but target browser info could also assist in helping you resolve your issue. Please consider adding it in future!
As for your problem, you tell us that you wish the video to autoplay, I'm assuming on page load?
I've also removed the duplicate source paste.
In this case, you only call playVid() from within the promise erroring out. The initial call is bound to the button click event.
In short, only clicking the button will initiate the playVid() function.
You need to add an event listener for DOM readiness and call playVid() within that. Otherwise, it's only being called when you click your button!
document.addEventListener('DOMContentLoaded', (event) => {
//the event occurred
playVid();
});
You can also use the autoplay HTML option in the video tag.
lang-html
<video {...} autoplay />
I had an almost similar problem ، when I received the video stream in a webrtc project, the video would not be displayed without clicking a button.
if you want to play automatically received stream video, you should add "muted" in the video tag.

Preload Javascript audio to play in script

I have a simple program where I run this script:
function PlayAudio(Location){
var audio = new Audio(Location);
audio.Play()
}
in an onclick HTML attribute. I have a fancy loading picture that I know how to make appear and have successfully made it work. I would like to show this picture while the audio is loading, and then make it go away after the audio file is done loading and ready to play. Right now, there is a considerable delay between clicking the element and hearing the sound.
My trouble is knowing when the audio is done loading and ready to play. I figure the best way to know when it's complete loading is to preload the file in-script. I don't know how to do that.
And that's my question:
How do you preload files inside a script?
Or, is there a way to know when an audio file is finally playing?
Note: I cannot use an <audio> element, unless there is some way to nest a <div> inside the <audio> so that the sound in the <audio> is triggered by clicking anywhere in the content of the <div>
Sorry for my slightly confusing descriptions!
Thanks,
Lucas N
You can use canplaythrough event
Sent when the ready state changes to CAN_PLAY_THROUGH, indicating that
the entire media can be played without interruption, assuming the
download rate remains at least at the current level.
function PlayAudio (Location){
var audio = new Audio;
audio.oncanplaythrough = function(event) {
// do stuff, e.g.; set loading `img` `style` `display` to `none`
this.play();
}
audio.src = Location;
}
You change its preload attr by
. audio.preload = "auto";
It will load the whole audio file on start

Playing random audio in HTML/Javascript

I am trying to figure out how to continuously play random audio sound bites, one after another without having them overlap on an HTML page using jquery. I have code that plays random sound bites on a timer, but sometimes they overlap and sometimes there is a pause in between the sounds. I had looked into ended and other EventListeners but I really have no idea what I am doing. Here is a portion my code:
<html>
<audio id="audio1">
<source src="cnn.mp3"></source>
</audio>
<audio id="audio2">
<source src="sonycrackle.mp3"></source>
</audio>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('audio').each(function(){
this.volume = 0.6;
});
var tid = setInterval(playIt, 2000);
});
function playIt() {
var n = Math.ceil(Math.random() * 2);
$("#audio"+n).trigger('play');
};
Is there a way to just continuously play these sounds bites one after another right after the previous sound plays? FWIW I have many sound bites but I am just showing two above for reference.
So I dabbled a bit, here's a full pure JavaScript solution.
Should be cross-browser, haven't tested (/lazy). Do tell me if you find bugs though
var collection=[];// final collection of sounds to play
var loadedIndex=0;// horrible way of forcing a load of audio sounds
// remap audios to a buffered collection
function init(audios) {
for(var i=0;i<audios.length;i++) {
var audio = new Audio(audios[i]);
collection.push(audio);
buffer(audio);
}
}
// did I mention it's a horrible way to buffer?
function buffer(audio) {
if(audio.readyState==4)return loaded();
setTimeout(function(){buffer(audio)},100);
}
// check if we're leady to dj this
function loaded() {
loadedIndex++;
if(collection.length==loadedIndex)playLooped();
}
// play and loop after finished
function playLooped() {
var audio=Math.floor(Math.random() * (collection.length));
audio=collection[audio];
audio.play();
setTimeout(playLooped,audio.duration*1000);
}
// the songs to be played!
init([
'http://static1.grsites.com/archive/sounds/background/background005.mp3',
'http://static1.grsites.com/archive/sounds/background/background006.mp3',
'http://static1.grsites.com/archive/sounds/background/background007.mp3'
]);
Some quick suggestions is add the attribute preload="auto" to the audio element and change the script to be $(window).onload instead of document ready. Document ready fires when html is in place but not necessarily when audio and other assets (like images) have loaded.
You could also look into using the AudioBuffer Interface in the new Web Audio API, it's described as "this interface represents a memory-resident audio asset (for one-shot sounds and other short audio clips)." which sounds like what you need. I believe part of the issues you're having (random pauses/delays/sound glitches with the audio element) are one of the reasons why it's being developed.
Read more here:
https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html#AudioBuffer
Unfortunately it's only Chrome and lastest Safari supported with Firefox support supposedly in the next 6(ish) months and no word yet on IE support.

HTML 5 <audio> - Play file at certain time point

I have a simple auto playing snippet that plays the audio file however I was wondering either in JavaScript or as an attribute play that file at a certain time (ex. 3:26).
<script type="text/javascript">
var myAudio=document.getElementById('audio2')
myAudio.oncanplaythrough=function(){this.play();}
</script>
<audio id="audio2"
preload="auto"
src="file.mp3"
oncanplaythrough="this.play();">
</audio>
Any help would be great. Thanks in advance :)
The best way to do this is to use the Media Fragment URI specification. Using your example, suppose you want to load the audio starting at 3:26 in.
<audio id="audio2"
preload="auto"
src="file.mp3#t=00:03:26"
oncanplaythrough="this.play();">
</audio>
Alternatively, we could just use the number of seconds, like file.mp3#t=206.
You can also set an end time by separating the start from the end times with a comma. file.mp3#t=206,300.5
This method is better than the JavaScript method, as you're hinting to the browser that you only want to load from a certain timestamp. Depending on the file format and server support for ranged requests, it's possible for the browser to download only the data required for playback.
See also:
MDN Documentation - Specifying playback range
W3C Media Fragments URI
A few things... your script will first need to be after the audio tag.
Also you don't need the oncanplaythough attribute on the audio tag since you're using JavaScript to handle this.
Moreover, oncanplaythrough is an event, not a method. Let's add a listener for it, which will instead use canplaythough. Take a look at this:
<audio id="audio2"
preload="auto"
src="http://upload.wikimedia.org/wikipedia/commons/a/a9/Tromboon-sample.ogg" >
<p>Your browser does not support the audio element</p>
</audio>
<script>
myAudio=document.getElementById('audio2');
myAudio.addEventListener('canplaythrough', function() {
this.currentTime = 12;
this.play();
});
</script>
And finally, to start the song at a specific point, simply set currentTime before you actually play the file. Here I have it set to 12 seconds so it will be audible in this example, for 3:26 you would use 206 (seconds).
Check out the live demo: http://jsfiddle.net/mNPCP/4/
EDIT: It appears that currentTime may improperly be implemented in browsers other than Firefox. According to resolution of this filed W3C bug, when currentTime is set it should then fire the canplay and canplaythrough events. This means in our example, Firefox would play the first second or so of the audio track indefinitely, never continuing playback. I came up with this quick workaround, let's change
this.currentTime = 12;
to test to see if it has already been set, and hence preventing the canplaythrough to get called repeatedly:
if(this.currentTime < 12){this.currentTime = 12;}
This interpretation of the spec is still currently being disputed, but for now this implementation should work on most modern browsers with support for HTML5 audio.
The updated jsFiddle: http://jsfiddle.net/mNPCP/5/
I have a simple answer that will work for all
1- create a button that when clicked it plays the audio/video
2- test that audio playing when you click the button if it works to hide the button and
3- click button when page loads
window.onload =function(){
document.getElementById("btn").click();
}

How do you check if a HTML5 audio element is loaded?

I am wanting to know how to check if a HTML5 audio element is loaded.
To find out when the audio is ready to start playing, add listeners for the oncanplay or oncanplaythrough events. To find out when the audio has loaded at all, listen to the onloadeddata event:
<audio oncanplay="myOnCanPlayFunction()"
oncanplaythrough="myOnCanPlayThroughFunction()"
onloadeddata="myOnLoadedData()"
src="myaudio.ogg"
controls>
Download
</audio>
<script>
function myOnCanPlayFunction() { console.log('Can play'); }
function myOnCanPlayThroughFunction() { console.log('Can play through'); }
function myOnLoadedData() { console.log('Loaded data'); }
</script>
Check out robertc's answer for how to use event listeners. You can also directly check an audio element's ready state:
var myAudio = $('audio')[0];
var readyState = myAudio.readyState;
readyState will be a number. From Mozilla's docs:
0 - No information is available about the media resource.
1 - Enough of the media resource has been retrieved that the metadata attributes are initialized. Seeking will no longer raise an exception.
2 - Data is available for the current playback position, but not enough to actually play more than one frame.
3 - Data for the current playback position as well as for at least a little bit of time into the future is available (in other words, at least two frames of video, for example).
4 - Enough data is available—and the download rate is high enough—that the media can be played through to the end without interruption.
Another option is networkState:
var myAudio = new Audio(url);
var networkState = myAudio.networkState;
networkState is a helpful companion property to the previously mentioned readyState, and can be handy in certain contexts where readyState might fall short, such as discerning whether or not a file is likely going to load at all. This can be done by checking it at set intervals.

Categories

Resources