javascript not executed with setTimeout but does with button click event - javascript

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.

Related

How do I get audio to play when I hover over an image?

I'am a complete beginner in coding I was just practicing making a simple prank web page for my nephew (its an inside joke of ours) I know the solution might be easy but I cannot figure it out on account of being a beginner and still learning. I want the audio to play when I hover my mouse on the image and to stop playing when my mouse is out how can I modify my code (given below) to do that?. I tried with the onclick event and it worked. Thank you in advance
</head>
<body>
<script>
function play(){
var audio = document. getElementById("audio")
audio.play();
}
</script>
<img src="moolikeacow.jpg" value="PLAY" onclick="play()">
<audio id="audio" src="rickroll.mp3"></audio>
</body>
I refactored your code a bit. First of all moving the script element to the end of the document to make sure that all elements are loaded before referring to them. Second I made event listeners for both click, mouseover and mouseout events. I also added a function for stopping the audio.
<body>
<img id="img" src="moolikeacow.jpg" />
<audio id="audio" src="rickroll.mp3"></audio>
<script>
var audio = document.getElementById("audio");
var img = document.getElementById("img");
function play() {
audio.play();
}
function stop() {
audio.pause();
}
img.addEventListener('click', play);
img.addEventListener('mouseover', play);
img.addEventListener('mouseout', stop);
</script>
</body>
The First Problem why it doesn't work is that you wrote javaScript top of the html elements as a result javaScript can't grab those elements because those elements are created after javaScript.
Second Problem is You Added The Click event to image so only if you click it will start the audio, not on hover. You should add the mouseover event listener instead of click to make that work.
I just wrote a script that works well as you are looking for and with good comments so you can use or learn how it's working
https://gist.github.com/mmestiyak/93b4ee8952337f7847e3aab4f6521174
You Used Inline Event in Image But There is much more things to do with addEventListener method that comes in every element you grab in javaScript.
You can give a look at MDN to know more about addEventListener
Here you can see the live version: https://h7qym.csb.app/
hover on the image and just wait for some seconds to see the magic
If Any other things to know please let me know, i enjoy help you
try this:
$('a').hover(function(){
PlaySound('mySound');// calling playsound function
},function(){
StopSound('mySound');// calling stopsound function
});
and change your anchor tag like,
Hover Over Me To Play

Stop/skip video manually on click

I am trying to end a video when a user clicks a skip button allowing a user to skip the video.
I have been using the following, which is all good, and allows me to trigger an action when the video ends.
HTML
<video autoplay>
<source src="video.mp4" type="video/mp4">
</video>
<button class="skip">Skip video</button>
JS
$('video').on('ended',function(){....
//do stuff here
}
however, I want to do something like the following, but not sure how to implement this.
$('.skip').click(function(){
$('video').end();
});
The end() method in jQuery using to get back to the previous selector.
Description from jQuery docs :
End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.
To stop the video get dom object and then use HTMLMediaElement#pause method. Although finally trigger the ended event programmatically using trigger() method.
$('.skip').click(function(){
$('video').trigger('ended')[0].pause();
});
$('.skip').click(function(){
$('video')[0].load();
$('video')[0].pause();
});
Moving a video to the end of playback is not a straightforward operation as you need to first get the length of the video, then move to that point.
A much simpler alternative is to extract the logic that's invoked under ended and call it when the button is clicked too. Try this:
$('video').on('ended', function() {
videoEnded();
})
$('.skip').click(function() {
$('video')[0].pause();
videoEnded();
});
function videoEnded() {
// do stuff here
}
Working example

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

Receive events from multiple HTML5 videos

I have multiple videos and want to get an event from all of them. But I get only the event from one of them (tested in Chrome). Why?
HTML:
<video id="video1" preload="auto" src="video1.ogg"></video>
<video id="video2" preload="auto" src="video2.ogg"></video>
JS:
$('video').on('canplay', function(){
console.log($(this).attr('id'));
});
jsFiddle
EDIT:
Ok.. it is really strange. On the very first load I get sometimes both events. But after that on every reload I get just an event from one of them!? Here a screenshot of my console:
The problem is that the 'canplay' event has already fired by the time you register it. I believe this is because jsFiddle wraps your code inside of $(window).load(.... If you were to move the script into the html, like on this example, it should work.
Most of the time, if you know for sure that your script is going to run synchronously right after the video element is created with a src, you can assume that none of those events have been fired. But, just to be safe, and especially when you don't know how your code will be used, I recommend something like this:
function handleCanplay(video) {
console.log($(video).attr('id'));
};
$('video').each(function () {
//first, check if we missed the 'canplay' event
if (this.readyState >= this.HAVE_FUTURE_DATA) {
//yup, we missed it, so run this immediately.
handleCanplay(this);
} else {
//no, we didn't miss it, so listen for it
$(this).on('canplay', function () {
handleCanplay(this);
});
}
});
Working example here.

Correct way to play <audio> + <video> from Javascript

I'm getting different results i Firefox and Chrome when using <audio> and <video> with preload="none" and then trying to play from Javascript.
Let's say i was using preload="auto" or preload="metadata" :
audio.src = "filename";
audio.play();
That seems to work fine in both Firefox and Chrome but i want to use preload="none" and then Chrome dossent play.
So i'm trying this code with preload="none" :
audio.src = url;
audio.load();
audio.addEventListener('canplay', function(e) {
audio.play(); // For some reason this dossent work in Firefox
}, false);
audio.play(); // Added this so Firefox would play
I don't know if that's the correct way to do it.
I'm using :
Firefox 20.0.1
Chrome 25.0.1364.172 m
I made a demo : http://netkoder.dk/test/test0217.html
Edit :
In the 2nd audio player (on the demo page) it seems that when using preload="none" you have to use load().
But is it correct to just use play() right after load() or is the correct way to use an event to wait for the file to load before playing it ?
In the 3rd audio player it seems Firefox 20.0.1 dossent support the canplay event correctly when used with addEventListener() because it dossent trigger after load(), it triggers after play() and also triggers when scrubbing though the sound which dossent seem to be the way the canplay should work.
Using .oncanplay does work.
So the following code seems to work :
function afspil2(url) {
afspiller2.src = url;
afspiller2.load(); // use load() when <audio> has preload="none"
afspiller2.play();
}
function afspil3(url) {
afspiller3.src = url;
afspiller3.load(); // use load() when <audio> has preload="none"
//afspiller3.addEventListener('canplay', function() { // For some reason this dossent work correctly in Firefox 20.0.1, its triggers after load() and when scrubbing
// afspiller3.play();
//}, false);
afspiller3.oncanplay = afspiller3.play(); // Works in Firefox 20.0.1
}
I updated the demo to include the changes : http://netkoder.dk/test/test0217.html
My way of adding addEventListener inside the afspil3() function dossent seem good because the first time the function is called the code inside addEventListener is called 1 time. The second time the function is called the code inside addEventListener is called 2 time and then 3 times and so on.
It's because your audio tags are missing the required src attribute, or <source> tags. When I added them in your demo, all 3 players immediately began working in both Chrome and FF.
Also, I recently discovered that src cannot be an empty string and subsequently changed with JS. If there's a reason you can't set the src in the HTML, your best alternative, IMO, is to create the audio elements with Javascript:
var audio = new Audio();
audio.src = url;
audio.controls = true;
audio.preload = false;
// and so on
Edit: Ok. It seems that in Chrome, when the HTML is preload="none" it is necessary to call load() before playing when the src is changed. Your second audio doesn't preload, so your function needs to be this:
function afspil2(url) {
afspiller2.src = url;
afspiller2.load(); // add load call
afspiller2.play();
}
Then, it seems that in Firefox, it is necessary to set preload="auto"; when attaching an event to the canplay event, like in the 3rd function.
function afspil3(url) {
afspiller3.src = url;
afspiller3.preload = "auto";
afspiller3.load();
afspiller3.addEventListener('canplay', function(e) {
this.play(); // For some reason this dossent work in Firefox
}, false);
}
That just seems very strange, but I tested it multiple times, and each time it would play if preload="auto" is called, but would not play if it isn't called. Note that it wasn't necessary for the 2nd player, which was also preload="none" in the HTML tag.
Finally, Chrome has some odd behaviors if there are multiple <audio> elements on the page. For all three players, reloading the page and clicking "the big electron" link would play correctly.
Reloading and then clicking "Yoda" on the 2nd or 3rd player won't do anything, but it WILL play for the first player. But, if the top player is played first by any means - play button or either link - then the other two "Yoda" links will suddenly work.
Also, if you click a 2nd or 3rd "Yoda" link first after reload, and then click the top player, the previously clicked "Yoda" (that didn't previously play) will begin to play on its own after the top player stops.
Suffice it to say they have some bugs to work out.
The correct way in my opinion would mean using an existing solution, like http://mediaelementjs.com/
If your really interested in the details on the best way to play audio and video with js then look at the source:
https://github.com/johndyer/mediaelement/tree/master/src/js
https://github.com/johndyer/mediaelement/blob/master/src/js/me-mediaelements.js

Categories

Resources