HTML 5 audio - Play file at certain time point
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/
HTML5 Audio Tag - Start and end at position
There is a timerange parameter available in MediaElement's src
attribute which does exactly this.
://url/to/media.ext#t=[starttime][,endtime]
Note that if you enable the controls on these elements, then the user will be able to seek to different positions.
Example :
var url = 'https://upload.wikimedia.org/wikipedia/commons/4/4b/011229beowulf_grendel.ogg';var slice_length = 12;var audio, start, end;for (var i = 0; i < 10; i++) { start = slice_length * i; // set the start end = slice_length * (i + 1); // set the end // simply append our timerange param audio = new Audio(url + '#t=' + start + ',' + end); audio.controls = true; // beware this allows the user to change the range
document.body.appendChild(document.createTextNode(start + 's ~ ' + end + 's')); document.body.appendChild(document.createElement('br')); document.body.appendChild(audio); document.body.appendChild(document.createElement('br'));}
How to play audio at a specific time in javascript
As adeneo's comment states, you need to have the conditional statement within the event function.
The following will call updateTime every second, and if the minute of the day is 39 and it is not playing, it will start playing audio. It will also call setTimeout
to stop the audio five minutes later.
Feel free to add the hour within the if
statement if you like.
var audio = new Audio('audio.mp3');
function updateTime(){
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
if (minutes == 39 && audio.paused) {
audio.play();
setTimeout(function() { audtio.pause(); }, 300000);
}
}
setInterval(updateTime, 1000);
Setting HTML5 audio position
Works on my chrome...
$('#audio').bind('canplay', function() {
this.currentTime = 29; // jumps to 29th secs
});
custom start and end points for html audio element
I did figure out something that works.
The canplaythrough
event won't suffice because the audio will be looping; this event is only fired once
As an alternative, I'm using the timeupdate
event: (this in coffeescript)
window.playbackStart = 2
window.playbackEnd = 4
$("audio").off("timeupdate").on "timeupdate", (e) ->
audio = e.currentTarget
if audio.currentTime > playbackEnd
audio.currentTime = playbackStart
this seems simple enough, but I had to do a little debugging because calling currentTime =
was not working (it was just setting the time to zero, no matter what). It turns out the issue was actually server-side (see https://stackoverflow.com/a/32667819/2981429).
I needed to:
Configure my server to use HTTP 1.1
with Nginx, I added
proxy_http_version 1.1;
proxy_set_header Connection "";to my
location { }
block
- In my application, set the header
Accept-Ranges: bytes
with the response.
Run a function when an HTML5 Audio Element has played a certain %
There may be a better way, but I could see you using the "duration" and "currentTime" properties of media elements in HTML5.
Untested, but this might get you unstuck:
function check(){
var duration = audioElement.duration;
var currentTime = audioElement.currentTime;
if( currentTime / duration >= 0.5 ){
halfway()
}
}
setInterval(check, 1000) //run this checker on an interval
HTML5 Audio: How to Play only a Selected Portion of an Audio File (audio sprite)?
I think there are a couple of problems here.
Firstly, you're adding an event listener every time the user clicks Play 1.
Also I think
if (currentTime >= 0.5) { ...
should be
if (audio.currentTime >= 0.5) { ...
This also works:
<audio id="sample" src="http://dl.dropbox.com/u/222645/click1sec.mp3" controls preload></audio>
<a href="javascript:playSegment(0.0, 0.5);">Play1</a>
<a href="javascript:playSegment(0.5);">Play2</a>
<script>
var audio = document.getElementById('sample');
var segmentEnd;
audio.addEventListener('timeupdate', function (){
if (segmentEnd && audio.currentTime >= segmentEnd) {
audio.pause();
}
console.log(audio.currentTime);
}, false);
function playSegment(startTime, endTime){
segmentEnd = endTime;
audio.currentTime = startTime;
audio.play();
}
</script>
html5 display audio currentTime
Here's an example:
<audio id="track" src="http://upload.wikimedia.org/wikipedia/commons/a/a9/Tromboon-sample.ogg"
ontimeupdate="document.getElementById('tracktime').innerHTML = Math.floor(this.currentTime) + ' / ' + Math.floor(this.duration);">
<p>Your browser does not support the audio element</p>
</audio>
<span id="tracktime">0 / 0</span>
<button onclick="document.getElementById('track').play();">Play</button>
This should work in Firefox and Chrome, for other browsers you'll probably need to add alternative encodings.
Related Topics
How to Get Old Value with Onchange() Event in Text Box
JavaScript Detect Click Event Outside of Div
How to Combine Jquery Animate with CSS3 Properties Without Using CSS Transitions
How to Get the Position of Element Transformed with CSS Rotate
Smoothly Stop CSS Keyframe Animation
Call Swift Function with JavaScript Using Uiwebview
Add Property to an Array of Objects
Syntaxerror: Use of Const in Strict Mode
Queryselector, Wildcard Element Match
Prevent Redirection of Xmlhttprequest
What Events Does an <Input Type="Number" /> Fire When Its Value Is Changed
How to Disable Copy Paste (Browser)
The Purpose of Starting an Initial Comment with /*! in JavaScript and CSS Files
Set the Webkit-Keyframes From/To Parameter with JavaScript
Filling Empty Cells in CSS Grid Layout
React 'Cannot Read Property of Undefined' When Using Map