InvalidStateError in IE11 when trying to rewind and pause video - javascript

I am building a website where videos start to play when you move the mousepointer over them. When a user leaves the video area it pauses and jumps back to the first frame. This works perfectly in every browser besides IE. When I open the dev console it shows me an "InvalidStateError" right above the part of code that handles the stop function. Why is IE behaving like that? Thanks for any input on this.
Here is the part of code that triggers the error:
var figure = $('.servus_video').hover(playVideo, stopVideo);
function playVideo(e) {
$('video', this).get(0).play();
}
function stopVideo(e) {
$('video', this).get(0).currentTime = 0;
$('video', this).get(0).pause();
}
Screenshot from IE11 debugger

Ok, after hours of troubleshooting I realized that IE responded with "Invalid Source" which I couldn't see because I disabled controls for the video. After tripple checking my encoder settings and verifying that they were correct I stumbled upon a document in which MS states that the maximum supported height of a video file is 1088px. 1088!? My videos were 720x1280px (portrait). After changing the resolution to 612x1088px everything worked.
https://msdn.microsoft.com/en-us/library/windows/desktop/dd797815(v=vs.85).aspx

Related

Audio file won't play when hovering over image - until a click event takes place on page [duplicate]

I'm trying to get a small sound file to play automatically using an tag and javascript to initiate it.
<audio id="denied" preload="auto" controls="false">
<source src="sound/denied.wav" />
</audio>
And then through javascript, at the appropriate time:
$('#denied')[0].play()
Works fine on Chrome on my desktop. In Android 4.1.1, the sound will not play, unless I hit "play" on the HTML5 audio controls before javascript attempts to play it.
So basically the Android browser (stock or Dolphin) will not play the audio unless the user initiates it at some point before the javascript. Is this intended? Is there any way around this?
Well, for my purposes, here's what I did:
Luckily, before the user can trigger the behavior to start audio, they have to click a button. I set the volume of the element to 0.0, and have it "play" when they click this button.
After the sound is played silently, I simply set the volume property back to 1.0, and it plays without user intervention just fine.
In my case this was an easy solution:
https://stackoverflow.com/a/28011906/4622767
Copy & paste this in your chrome:
chrome://flags/#autoplay-policy
My web app has many page reload so I can't force the user to press a button every time; but it is for internal usage, so I can force the users to use chrome and configure that option.
I know that in mobile safari any javascript call to play() must be in the same call stack as a user initialted click event. Spoofing the the click with a javascript trigger won't work either.
On my nexus 7 I can confirm that unless the javascript was triggered by a user click, it does not play.
The main issue is that sound (on iOS and Android) must be triggered by a user click. My workaround was very simple. Tie the audio.play() to a click event listener and then immediately pause it. From that point and on the sound works perfect.
var myAudio = new Audio('assets/myAudio.mp3');
...
button.addEventListener("click", function() {
myAudio.play();
myAudio.pause();
...
});
Here is a blog-post on the reason and how to overcome it by loading all the audio files on first user interaction and play them later in programmed manner: https://blog.foolip.org/2014/02/10/media-playback-restrictions-in-blink/ Adopting this approach a small javascript module is available on GitHub https://github.com/MauriceButler/simple-audio
I tried this simple approach on my own - worked seamlessly & great!
Luckily for me the html5 app I'm working on only needs to work in Android 4.1, but if you're trying to make something cross-platform you'll need to adapt this slightly. Neither setting volume to 0.0 then back or autoplay on the control worked for me. I also tried muted and that didn't work either. Then I thought, what if I set the duration and only play a miniscule amount of the file? Here's yet another hacked-together script that actually did work:
function myAjaxFunction() {
clearTimeout(rstTimer); //timer that resets the page to defaults
var snd=document.getElementById('snd');
snd.currentTime=snd.duration-.01; //set seek position of audio near end
snd.play(); //play the last bit of the audio file
snd.load(); //reload file
document.getElementById('myDisplay').innerHTML=defaultDisplay;
var AJAX=new XMLHttpRequest(); //won't work in old versions of IE
sendValue=document.getElementById('myInput').value;
AJAX.open('GET', encodeURI('action.php?val='+sendValue+'&fn=find'), true);
AJAX.send();
AJAX.onreadystatechange=function() {
if (AJAX.readyState==4 && AJAX.status==200) {
document.getElementById('myDisplay').innerHTML=AJAX.responseText;
if (document.getElementById('err')) { //php returns <div id="err"> if fail
rstTimer = setTimeout('reset()', 5000); //due to error reset page in 5 seconds
snd.play(); //play error sound
document.getElementById('myInput').value=''; //clear the input
}
}
}
}
You don't need JavaScript for autoplay, and I see several issues in your code:
<audio id="denied" preload="auto" controls="false">
<source src="sound/denied.wav" />
</audio>
I'd change it to (in HTML5 you don't need attribute="value" syntax in some cases, that's for XHTML):
<audio id="denied" autobuffer controls autoplay>
<source src="sound/denied.wav" />
</audio>
play!
In iOS autoplay is disabled, you need to click play button or put a user click event on custom controls like this with JavaScript:
var audio = document.getElementById('denied');
var button = document.getElementById('play-button');
button.addEventListener('click',function(){
audio.play();
});
or with jQuery:
$('#play-button').click(function(){ audio.play(); });}
Edit
Keep in mind that HTML5 is pretty recent technology (at least some functionalities), so browser compatibility and functionality changes every once in a while.
I encourage everybody to keep informed about the current status, as sometimes things start to be less hack-dependant, or the other way around.
A good starting point: http://caniuse.com/#feat=audio (check the tabs at the bottom).
Also for a global audio solution I recommend using SoundManager2 JS library
I met the same problem in my app. My application usage scenario was like this:
click the button to show a table with information (user action)
show the table and refresh data in it by AJAX
play sound when data has been changed
Fortunately I had the user action (step 1) so I was able to "initiate" the sound by it and then play it by javascript without the user action needed. See the code.
HTML
<audio id="kohoutAudio">
<source src="views/images/kohout.mp3">
</audio>
<button id="btnShow">Show table</button>
Javascript
$("#btnShow").click(function () {
//some code to show the table
//initialize the sound
document.getElementById('kohoutAudio').play();
document.getElementById('kohoutAudio').pause();
});
function announceChange(){
document.getElementById('kohoutAudio').play();
};
It happened to me too. Here's how I hacked this:
I set the audio to autoplay and set the vol to 0.
When I need it to play, I use the load() method and it will autoplay.
It's a light mp3 file and it plays every one hour/two hour, so this works fine for me.

Audio files (.mp3) don't play on page reload, only once when VS code/Live Server extension auto-reloads on save

Tested on Chrome/Firefox/Edge. I'm working on Win10 with VS code and the "Live Server" extension.
The page loads, first audio file(.mp3) plays, then different elements appear with Jquery delays, etc. Upon a certain < ul > fading in, the second audio file plays.
With "Live Server" 's auto-reloading on save feature or by clicking on my navbar's link to the same page (testing purposes), the sounds and Jquery functions work fine, but if I refresh with the browser itself, the sound files don't play again.
I tried solutions found on google, like setting currentTime, onLoad, but they didn't really answer a similar problem, the most success I've had was achieving the same results I had from the start.
I'm just starting to learn JS and Jquery, so I'm sorry if the code is messy.
<script type="text/javascript" src="script/jquery-3.5.1.min.js"></script>
<script type="text/javascript" src="script/main.js"></script>
<script>
var audio1 = $("#mantra")[0];
var audio2 = $("#wind")[0];
audio1.play()
$("document").ready(function () {
$(".choix").hide() // .choix is the class of fig1, fig2, fig3, fig4
$("#fig1").delay(9500).fadeIn(3000);
$("#fig2").delay(9550).fadeIn(3000);
$("#fig3").delay(9600).fadeIn(3000);
$("#fig4").delay(9650).fadeIn(3000);
$("#tagline").hide().delay(2000).fadeIn(1500)
.delay(1500).fadeOut(2000).queue(function(n) {
$(this).html("<br> Start here");
n();
}).delay(700).fadeIn(2000);
$(".textNav").hide().delay(800).fadeIn(1500);
});
$("#wind").stop("true").delay(9400).queue(function() { //9400ms delay to start just before fig1+
audio2.play()
});
});
</script>
In cases when the audio is not playing, check the console and you will find an error stating
DOMException: play() failed because the user didn't interact with the
document first.
This is because browsers don't allow music autoplay on page-load. It is necessary for the user to make some interaction (click, tap, etc.) with the window before playing the audio.
Source

Website toggling full screen mode in Chrome, after ajax load

I still fighting with one Chrome issue on my webpage. There is pagination, that loads content via ajax call:
https://elody.cz/nase-nevesty
When I click 2nd, 3d, .. tab in pagination. The load is being performed and after that, it jumps into fullscreen mode.
You can also check on this video:
https://www.loom.com/share/768557e080f1471393aa0377d3fec024
I have this issue on Mac as well as on Windows – in Chrome.
Please, do anybody know how to fix that?
Thank you!
Filip
Inside ba_gallery.js there is following line:
var fullscreen = true;
set this value to false may solve your problem, i guess its worth a try
After ajax is done you could verify if its in fullscreen mode, if yes set its to false.
document.fullscreenEnabled : test id browser supports fullscreen
document.documentElement.requestFullscreen(); turn your page in to fullscreen
document.addEventListener("fullscreenchange", function (event) {
if (document.fullscreenElement) {
// fullscreen is activated
} else {
// fullscreen is cancelled
}
});
testing if its in full screen
document.exitFullscreen(); getting out

javascript. alert when sound plays

I am basically trying to make a auto better on earn.gg (dice)
Is there a way to alert("win") if a sound is playing in the chrome tab? I will run the script in the console of that tab.
I have tried to do "roll();" in the console and it rolled the dice and returned me "value:false" because i lost and when i win it returns me value:true.So i figured to use that and make the code below. That simply didn't work and returned me "win" every time. Screenshot: http://prntscr.com/fpeoxb
roll();
if(value=true){
console.log("win");
}else if(value=false){
console.log("lose");
}

Click event not triggering over youtube iframe in mobile safari

I’d like to place interaction controls above a youtube iframe video, and I got it working quite OK by just adding wmode=opaque as arguments and then position the elements absolute above the iframe.
My problem is that on mobile safari - the controls work fine first, but when I return from the fullscreen video, they are all disabled. It works fine on desktop though.
The HTML is basically:
<iframe src="http://www.youtube.com/embed/[ID]?wmode=opaque"></iframe>
<button id="btn">Click me</button>
And then the button is positioned absolute above the iframe.
For a demo, please visit this fiddle using your mobile safari: http://jsfiddle.net/SwGH5/embedded/result/
You’ll see that the button yields an alert when clicked. Now, play the video and click "done". Then try to click the button again...
If the movie was embedded using the <video> tag I could listen for a fullscreen-end event and do something, but now I’m stuck...
Here’s the fiddle: http://jsfiddle.net/SwGH5
So I played around with the iframe API a bit and found a solution. It's kind of hacky... but not really. When a user clicks on the video to play it, the document.activeElement becomes the iframe. When the user clicks the "done" button, the document.activeElement === document.body. So when the video starts playing, we periodically check to see if the active element returns to the body. At that point, the only solution I found was to redraw the iframe. In the example, I destroy() the video and recreate it using the iframe API. I also tried cloning the iframe and replacing it with success (I left that code there so you could see it):
http://jsfiddle.net/ryanwheale/SwGH5/105/
It's not the best solution, but it works. Also, to give an explanation of what [I think] is happening - iOS hijacks any video content (Safari or Chrome) and plays it using the native video player. Any type of OS functionality like this takes place "over" the browser if you will - higher than any z-index... completely outside the browser. When the user clicks "done" the native player kind of zooms out as if it is re-implanting itself on the page. My best guess is that the native player is still hanging out "over" the browser... thus making anything underneath it inaccessible. The fact that the button appears to be on top is just an anomaly... for lack of better description.
EDIT: Ryan Wheale's solution is a better workaround to this problem and will work in most cases.
From Apple’s documentation:
On iOS-based devices with small screens—such as iPhone and iPod touch—video always plays in fullscreen mode, so the canvas cannot be superimposed on playing video. On iOS-based devices with larger screens, such as iPad, you can superimpose canvas graphics on playing video, just as you can on the desktop.
Same goes for a "played video" either. This article clearly states it's not possible.
Workaround:
You could detach and re-attach the iframe element on webkitfullscreenchange. But it won't work for a foreign iframe. Browser will not allow you to manipulate iframe DOM bec. of the cross-domain policy. And even if it did, you could only hide the video overlay to reach your button anyway.
So, the only solution is watching for YT.PlayerState.ENDED state via YouTube iFrame API and then destroying and re-creating the player. But don't worry it plays smooth.
window.onYouTubeIframeAPIReady = function () {
var video = {
player: null,
create: function () {
// first destroy if we already have the player
if (video.player) { video.player.destroy(); }
// create the player
video.player = new YT.Player('ytp', {
videoId: '9u_hp7zPir0',
width: '620',
height: '290',
events: {
'onStateChange': video.onStateChange
}
});
},
onStateChange: function (event) {
// YT.PlayerState.ENDED » exiting full screen
if (event.data === 0) { video.create(); }
}
};
video.create();
};
Here is the working fiddle.
If you can't get it to work with the regular iframe, you might want to consider using mediaelement.js - which can wrap the Youtube API in a HTML5 Media API wrapper. That works fine on safari on ios - try the Youtube example at mediaelementjs.com.
All you need to do is to add the mejs js/css and put your youtube video as source in your video tag, here is some example markup taken from mediaelementjs.com:
<script src="jquery.js"></script>
<script src="mediaelement-and-player.min.js"></script>
<link rel="stylesheet" href="mediaelementplayer.css" />
<video width="640" height="360" id="player1" preload="none">
<source type="video/youtube" src="http://www.youtube.com/watch?v=nOEw9iiopwI" />
</video>
Then start the player like so:
jQuery(document).ready(function($) {
$('#player1').mediaelementplayer();
});
If you want to add your button ontop of the mejs player it will work fine, just set the z-index high enough. If you want a regular play button you could also consider styling the existing one that comes with mejs.
By the comments from #CullenJ's answer, possibly it might be due to some problem in iOS device browsers not triggering the click event on iframe elements. In that case, you would have to change from:
document.getElementById('btn').onclick = function() {
alert('clicked');
}
To something like this (as answered by #smnh):
$('#btn').on('click tap touchstart', function() {
alert('clicked');
});

Categories