javascript - video play not working in setInterval - javascript

I am trying to play video using .play().
This is for in app with mraid, only native javascript.
I'm trying to play a video with .play(), it works only when the video is loaded.
var video = document.getElementById('video');
video.play();
the above simple 2 lines works like a charm, only when the video is loaded.
Therefore i have to make sure the video is loaded by using setInterval
var autoplay = setInterval(function(){
var video = document.getElementById('extVideo-tab1');
if(video !== null)
{
video.play();
clearInterval(autoplay);
}
},500);
Im very certain that it went into the if, but the video is not played.
Can't figure out why it is not working.
Please help, THANK YOU!

as an alternative, you could try using readyState, as:
var video = document.getElementById('video');
if( video.readyState === 4) {
// 4 -> HAVE_ENOUGH_DATA
//Enough data is available, the media can be played through to the end without interruption.
video.play();
}

Depending on your use case I suggest one of the two following potential solutions:
If you always want it to play right away, do:
video.autoplay = true;
or you could use readyState:
var autoplay = setInterval(function(){
var video = document.getElementById('extVideo-tab1');
if(video.readyState === 4)
{
video.play();
clearInterval(autoplay);
}
},500);

Is there a reason you cant use the autoplay attribute?
https://developer.mozilla.org/en/docs/Web/HTML/Element/video
Regardless you should use the onloadedmetadata event or similar that way you know when you can start playing or seek to a point (unless im missing something?)
document.getElementById('extVideo-tab1').addEventListener('loadedmetadata', function() {
this.play();
}, false)

Related

Do Action After audio.ended

Trying to learn some simple JS stuff with audio since I do a lot of audio work I figured I would learn how to embed some into a site of mine, not to mention just brush up on some simple web programming.
I wanted to have an action after the audio file finished playing however a while(1) loop checking audio.ended immediately crashes.
I decided to use setInterval to check every second however this does not seem to work either. No crash but nothing happens. I've checked through the Mozilla documentation and as far as I can see with my limited experience there is no obvious solution.
var audio = document.createElement('audio');
audio.id = 'audio';
audio.src = 'track01.mp3';
audio.play();
setInterval(checkFinished(), 1000);
function checkFinished()
{
if(audio.ended == false)
{
document.write(audio.ended.toString());
}
else
{
document.write(audio.ended.toString());
foo();
}
}
You should use an Event, instead.
var audio = document.createElement('audio'); audio.id = 'audio';
audio.src = 'track01.mp3';
document.body.appendChild(audio); // append somewhere else if wanted
audio.play();
audio.onended = function(){
console.log('You do say.');
}
As said by PHPglue, you can use .onended.
here's an example:
<audio id="myAudio" controls>
<source src="track01.mp3" type="audio/mpeg">
</audio>
<script>
var aud = document.getElementById("myAudio");
aud.onended = function() {
alert("The audio has ceased");
};
</script>
(I don't like needless js, but the script part is still applicable of you just use js for the audio)
Check out http://www.w3schools.com/tags/av_event_ended.asp for some info

Use javascript to detect if an MP4 video has a sound track

I am creating a custom controller for MP4 video on a web page. The controller includes a volume slider. Some of the videos that are to be played have no sound track. It would be good to disable the volume slider for these videos, so that the user is not confused when changing the position of the volume slider has no effect.
Is there a property or a trick for checking if an MP4 file has an audio track? (jQuery is an option).
Edit: using #dandavis's suggestion, I now have this solution for Chrome (and .ogg on Opera):
var video = document.getElementById("video")
var volume = document.getElementById("volume-slider")
function initializeVolume() {
var enableVolume = true
var delay = 1
if (video.webkitAudioDecodedByteCount !== undefined) {
// On Chrome, we can check if there is audio. Disable the volume
// control by default, and reenable it as soon as a non-zero value
// for webkitAudioDecodedByteCount is detected.
enableVolume = false
startTimeout()
function startTimeout () {
if (!!video.webkitAudioDecodedByteCount) {
enableVolume = true
toggleVolumeEnabled(enableVolume)
} else {
// Keep trying for 2 seconds
if (delay < 2048) {
setTimeout(startTimeout, delay)
delay = delay * 2
}
}
}
}
toggleVolumeEnabled(enableVolume)
}
function toggleVolumeEnabled(enableVolume) {
volume.disabled = !enableVolume
}
The video.webkitAudioDecodedByteCount value is initially 0. In my tests, it may take up to 256ms to get populated with a non-zero value, so I have included a timeout to keep checking (for a while).
There might be a better way of doing this, although it's fairly simple just using regular javascript for webkit or mozilla enabled browsers. webkit utilizes this.audioTracks and mozilla uses this.mozHasAudio respectively:
document.getElementById("video").addEventListener("loadeddata", function() {
if ('WebkitAppearance' in document.documentElement.style)
var hasAudioTrack = this.audioTracks.length;
else if (this.mozHasAudio)
var hasAudioTrack = 1;
if (hasAudioTrack > 0)
alert("audio track detected");
else
alert("audio track not detected");
});
<video id="video" width="320" height="240" controls>
<source src="http://media.w3.org/2010/05/video/movie_300.mp4" type="video/mp4">
</video>
There's also a function this.webkitAudioDecodedByteCount, however, I've never had any luck making it work.
There are different ways to check whether a video file has audio or not, one of which is to use mozHasAudio, video.webkitAudioDecodedByteCount and video.audioTracks?.length properties of video, clean and simple...

Seamless HTML5 Video Loop

I have searched extensively to find a solution to this but have not succeeded.
I have created a 4 second video clip that loops seamlessly in an editor.
However when the clip runs in a page via Safari, Chrome or Firefox there is a small but noticeable pause in the playback from end back to beginning.
I have tried using the loop and preload attributes both together and independently.
I have also tried the following javascript:
loopVid.play();
loopVid.addEventListener("timeupdate", function() {
if (loopVid.currentTime >= 4) {
loopVid.currentTime = 0;
loopVid.play();
}
}
But in all cases the momentary pause remains and spoils the effect.
I'm open to any ideas?
Since this question is a top search result in Google, but doesn't "technically" have an answer yet, I'd like to contribute my solution, which works, but has a drawback. Also, fair warning: my answer uses jQuery.
It seems the slight pause in the video loop is because it takes time for html5 video to seek from one position to another. So it won't help anything to try to tell the video to jump to the beginning when it ends, because the seek will still happen. So here's my idea:
Use javascript to clone the tag, and have the clone sit hidden, paused, and at the beginning. Something like this:
var $video = $("video");
var $clone = $video.clone();
$video.after($clone);
var video = $video[0];
var clone = $clone[0];
clone.hidden = true;
clone.pause();
clone.currentTime = 0;
Yes, I used clone.hidden = true instead of $clone.hide(). Sorry.
Anyway, after this the idea is to detect when the original video ends, and then switch to the clone and play it. That way there is only a change in the DOM as to which video is being shown, but there is actually no seeking that has to happen until after the clone starts playing. So after you hide the original video and play the clone, you seek the original back to the beginning and pause it. And then you add the same functionality to the clone so that it switches to the original video when it's done, etc. Just flip flopping back and forth.
Example:
video.ontimeupdate = function() {
if (video.currentTime >= video.duration - .5) {
clone.play();
video.hidden = true;
clone.hidden = false;
video.pause();
video.currentTime = 0;
}
}
clone.ontimeupdate = function() {
if (clone.currentTime >= clone.duration - .5) {
video.play();
clone.hidden = true;
video.hidden = false;
clone.pause();
clone.currentTime = 0;
}
}
The reason I add the - .5 is because in my experience, currentTime never actually reaches the same value as duration for a video object. It gets pretty close, but never quite there. In my case I can afford to chop half a second off the end, but in your case you might want to tailor that .5 value to be as small as possible while still working.
So here's my entire code that I have on my page:
!function($){
$(document).ready(function() {
$("video").each(function($index) {
var $video = $(this);
var $clone = $video.clone();
$video.after($clone);
var video = $video[0];
var clone = $clone[0];
clone.hidden = true;
clone.pause();
clone.currentTime = 0;
video.ontimeupdate = function() {
if (video.currentTime >= video.duration - .5) {
clone.play();
video.hidden = true;
clone.hidden = false;
video.pause();
video.currentTime = 0;
}
}
clone.ontimeupdate = function() {
if (clone.currentTime >= clone.duration - .5) {
video.play();
clone.hidden = true;
video.hidden = false;
clone.pause();
clone.currentTime = 0;
}
}
});
});
}(jQuery);
I hope this will be useful for somebody. It works really well for my application. The drawback is that .5, so if someone comes up with a better way to detect exactly when the video ends, please comment and I will edit this answer.
I've found that Firefox will stutter while looping if I'm using mp4 or ogv files. I changed the code in my page to try using a webm file first instead, and suddenly the stutter was gone and the video looped seamlessly, or at least close enough that I didn't see an issue. If you haven't given that a shot, it could be worth it to try converting the file to a webm format and loading that instead.

HTML 5 audio .play() delay on mobile

I just built a real-time app using socket.io where a "master" user can trigger sounds on receiving devices (desktop browsers, mobile browsers). That master user sees a list of sound files, and can click "Play" on a sound file.
The audio playback is instant on browsers. On mobiles however, there is a 0.5-2 seconds delay (my Nexus 4 and iPhone 5 about 1 second and iPhone 3GS 1-2 seconds).
I've tried several things to optimize the audio playback to make it faster on mobiles. Right now (at the best "phase" of its optimization I'd say), I combine all the mp3's together in one audio file (it creates .mp3, .ogg, and .mp4 files). I need ideas on how I can further fix / improve this issue. The bottleneck really seems to be in the hmtl 5 audio methods such as .play().
On the receivers I use as such:
<audio id="audioFile" preload="auto">
<source src="/output.m4a" type="audio/mp4"/>
<source src="/output.mp3" type="audio/mpeg"/>
<source src="/output.ogg" type="audio/ogg"/>
<p>Your browser does not support HTML5 audio.</p>
</audio>
In my JS:
var audioFile = document.getElementById('audioFile');
// Little hack for mobile, as only a user generated click will enable us to play the sounds
$('#prepareAudioBtn').on('click', function () {
$(this).hide();
audioFile.play();
audioFile.pause();
audioFile.currentTime = 0;
});
// Master user triggered a sound sprite to play
socket.on('playAudio', function (audioClip) {
if (audioFile.paused)
audioFile.play();
audioFile.currentTime = audioClip.startTime;
// checks every 750ms to pause the clip if the endTime has been reached.
// There is a second of "silence" between each sound sprite so the pause is sure to happen at a correct time.
timeListener(audioClip.endTime);
});
function timeListener(clipEndTime) {
this.clear = function () {
clearInterval(interval);
interval = null;
};
if (interval !== null) {
this.clear();
}
interval = setInterval(function () {
if (audioFile.currentTime >= clipEndTime) {
audioFile.pause();
this.clear();
}
}, 750);
}
Also considered blob for each sound but some sounds can go for minutes so that's why I resorted to combining all sounds together for 1 big audio file (better than several audio tags on the page for each clip)
Instead of pausing / playing, I simply set the volume to 0 when it shouldn't be playing, and back to 1 when it should be playing. The Audio methods currentTime and volume don't slow the audio playback at all even on an iPhone 3GS.
I also added the 'loop' attribute to the audio element so it never has to be .play()'ed again.
It was fruitful to combine all mp3 sounds together because this solutions can work because of that.
Edit: audioElement.muted = true or audioElement.muted = false makes more sense.
Edit2: Can't control volume on user's behalf on iOS so I must pause() and play() the audio element as opposed to just muting and unmuting it.
Your setup is working well on desktop because of the preload attribute.
Unfortunately, here's Apple on the subject of preload:
Safari on iOS never preloads.
And here's MDN:
Note: This value is often ignored on mobile platforms.
The mobile platforms are making a tradeoff to save battery and data usage to only load media when it's actually interacted with by the user or programmatically played (autoplay generally doesn't work for similar reasons).
I think the best you're going to do is combining your tracks together, as you said you've done, so you don't have to pay the initial load-up "cost" as much.
I was having the same delay issue when testing in mobile. I found out what some HTML 5 games are using for audio since games demand very low latencies. Some are using SoundJS. I recommend you try that library out.
You can find a speed comparison between using the HTML Audio tag vs using SoundJS here:
http://www.nickfrazier.com/javascript/audio/ui/2016/08/14/js-sound-libraries.html
(test in mobile to hear the difference)
From my tests SoundJS is much faster.
In fact, it's Good enough to be used in a game, or for sound feedback in a user interface.
Old question but here is my solution using one of the answer above:
const el = document.createElement("audio");
el.muted = true;
el.loop = true;
const source = document.createElement("source");
source.src = lineSe;
source.type = "audio/mpeg";
el.appendChild(source);
// need to call this function after user first interaction, or safari won't do it.
function firstPlay() {
el.play();
}
let timeout = null;
function play() {
// In case user press the button too fast, cancel last timeout
if (lineSeTimeout) {
clearTimeout(timeout);
}
// Back to beginning
el.currentTime = 0;
// unmute
el.muted = false;
// set to mute after the audio finish. In my case 500ms later
// onended event won't work because loop=tue
timeout = setTimeout(() => {
// mute audio again
el.muted = true;
}, 500);
}

Audio in a tool tip/hover?

I would like to include audio that will automatically play when the user scrolls over. I have not found a tooltip that will do this. Does anyone know of a way to accomplish this?
(Note: The user will be warned about the audio before they have access to the page.)
UPDATE
I got this working thanks to Bakudan - хан ювиги. But is there a flash fall back available using Bakudan - хан ювиги's method? Thanks!
UPDATE 2
Using Bakudan - хан ювиги's recommended method for adding a flash fallback using swfobject leaves me a bit confused. My lack of javascript knowledge is where I get lost. Here is the code I am using for my audio:
<script>
// Mouseover/ Click sound effect- by JavaScript Kit (www.javascriptkit.com)
// Visit JavaScript Kit at http://www.javascriptkit.com/ for full source code
var html5_audiotypes={ //define list of audio file extensions
"mp3": "audio/mpeg",
"ogg": "audio/ogg",
}
function createsoundbite(sound){
var html5audio=document.createElement('audio')
if (html5audio.canPlayType){ //check support for HTML5 audio
for (var i=0; i<arguments.length; i++){
var sourceel=document.createElement('source')
sourceel.setAttribute('src', arguments[i])
if (arguments[i].match(/\.(\w+)$/i))
sourceel.setAttribute('type', html5_audiotypes[RegExp.$1])
html5audio.appendChild(sourceel)
}
html5audio.load()
html5audio.playclip=function(){
html5audio.pause()
html5audio.currentTime=0
html5audio.play()
}
return html5audio
}
else{
return {playclip:function(){throw new Error(
"Your browser doesn't support HTML5 audio unfortunately")}}
}
}
//Initialize sound clips with 1 fallback file each:
var mouseoversound=createsoundbite(
"/messages4u/2011/images/october/laugh.ogg",
"/messages4u/2011/images/october/laugh.mp3")
</script>
I changed the else to the flash instead of the error message. How do I change this using swfobject to play the flash audio file? I am a bit lost by that.
Thanks for the help!
This is a good start. I`ve made a demo. If the audio is a little bit longer, add stopclip function to the createsoundbite function and then add it to the .mouseleave.
Edit:
To add flash change the else part. I'm very familiar with flash, but basically use one of the following:
create object - "document.createElement("object");... etc"
or which I think is better use swfobject
Here's a version that plays sound in older browsers and does not require flash:
var sound = document.createElement("audio");
if (!("src" in sound)) {
sound = document.createElement("bgsound");
}
document.body.appendChild(sound);
function playSound(src) {
sound.src = src;
sound.play && sound.play();
}
...
playSound("/sounds/something.mp3");
Edit: Here's a version that uses .hover() to play the sound when the mouse hovers over your element:
$(function) {
var sound = document.createElement("audio");
if (!("src" in sound)) {
sound = document.createElement("bgsound");
}
document.body.appendChild(sound);
$(".playable").hover(function() {
sound.src = this.soundFile;
sound.play && sound.play();
}, function() {
sound.src = "";
});
});
Set up your elements that you want to play a sound with a class of "playable" and custom attribute "soundFile" containing the source url for the sound file:
<span class="playable" soundFile="/sounds/something.mp3">Something</span>
<span class="playable" soundFile="/sounds/somethingElse.mp3">Something else</span>
soundmanager2

Categories

Resources