I have an html video that I'm trying to render on ios but the video won't autoplay. I found similar questions mentioning to use "playsinline" but I tried this approach and it doesn't fix the issue in my case. Here is how I'm currently displaying the video in Html:
<video class="remoteVideo" playsinline autoplay muted>
<source src="https://192.168.1.134:7278/GetVideo" type="video/mp4;" />
</video>
This gets streamed from some C# .NET Core code:
FileStream fileStream = new FileStream(path, FileMode.Open);
var result = new FileStreamResult(fileStream, contentType)
{
EnableRangeProcessing = true
};
return result;
This approach works great in chrome but on ios its getting this issue where it won't autoplay. If I add "controls" to the video in html then the play button will appear on ios and I can press play and the video will start playing. However, I'm looking to get the video to autoplay and without the video controls.
So, I'm not exactly sure why but, Changing my html to this (with the src specified directly in the video html rather than in a sub "source" html class) fixed the issue:
<video class="remoteVideo" src="https://192.168.1.134:7278/GetVideo" playsinline loop muted autoplay></video>
I have a project where I am to watch a video for specific information and select a choice then click submit, then the next video is loaded. The loading between videos tends to be upwards of 5 seconds and I would like to have the videos preloaded.
How can I edit the source code of the page to preload the next videos before clicking submit?
Here is what it looks like
You can use the preload attribute in the HTML5 video tag.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video
See the note also about it being a hint - most browsers currently follow it:
Note:
The autoplay attribute has precedence over preload. If autoplay is specified, the browser would obviously need to start downloading the video for playback.
The specification does not force the browser to follow the value of this attribute; it is a mere hint.
The snippet below shows an example. Note that it is important you videos are optimised for streaming also if they are mp4 with the header at the start - see YouTube recommendations:https://support.google.com/youtube/answer/1722171?hl=en and the info with the Quickstart tool here: https://github.com/danielgtaylor/qtfaststart
You can use this tool, ffmpeg, Handbrake etc to make this optimisation - for example: https://stackoverflow.com/a/50914703/334402
var vid1 = document.getElementById("MyVid1");
var vid2 = document.getElementById("MyVid2");
vid1.onloadeddata = function() {
vid1.currentTime = 882; //Go to end of video for this illustration
vid1.play()
};
vid2.onloadeddata = function() {
vid2.pause()
};
nextVideoStart = function() {
vid2.play()
};
<video id="MyVid1" width="320" height="176" controls preload="auto">
<source src="http://peach.themazzone.com/durian/movies/sintel-1024-surround.mp4" type="video/mp4">
Your browser does not support this video format
</video>
<video id="MyVid2" width="320" height="176" controls preload="auto">
<source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/mp4">
Your browser does not support this video format
</video>
<p></p>
<button onclick="nextVideoStart()">Click for next video</button>
Audio autoplay is working in Mozilla, Microsoft Edge and old Google Chrome as well but not in Google Chrome 67+ due to a policy change for autoplay.
They have blocked the autoplay (until specific session conditions are met as specified in the linked blogpost). How can one make audio autoplay in Google Chrome 67+?
Solution #1
My solution here is to create an iframe
<iframe src="audio/source.mp3" allow="autoplay" style="display:none" id="iframeAudio">
</iframe>
and audio tag aswell for non-chrome browsers
<audio autoplay loop id="playAudio">
<source src="audio/source.mp3">
</audio>
and in my script
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
if (!isChrome){
$('#iframeAudio').remove()
}
else {
$('#playAudio').remove() // just to make sure that it will not have 2x audio in the background
}
Solution #2:
There is also another workaround for this according to #Leonard
Create an iframe that doesn't play anything just to trigger the autoplay in the first load.
<iframe src="silence.mp3" allow="autoplay" id="audio" style="display: none"></iframe>
good source for the mp3 file silence.mp3
Then play your real audio file at ease.
<audio id="player" autoplay loop>
<source src="audio/source.mp3" type="audio/mp3">
</audio>
Personally I prefer solution #2 because it is cleaner approach for not relying so much in JavaScript.
Update August 2019
Solution #3
As an alternative we can use <embed>
For Firefox
It seems that audio auto-play is working so we don't need the <embed> element because it will create double audio running.
// index.js
let audioPlaying = true,
backgroundAudio, browser;
browser = navigator.userAgent.toLowerCase();
$('<audio class="audio1" src="audio.mp3" loop></audio>').prependTo('body');
if (!browser.indexOf('firefox') > -1) {
$('<embed id="background-audio" src="audio.mp3" autostart="1"></embed>').prependTo('body');
backgroundAudio = setInterval(function() {
$("#background-audio").remove();
$('<embed id="background-audio" src="audio.mp3"></embed>').prependTo('body');
}, 120000); // 120000 is the duration of your audio which in this case 2 mins.
}
Also if you have a toggle event for your audio make sure to remove the created <embed> element for audio.
Note: After your toggle, it will restart from the beginning because the <embed> is already deleted and the <audio> element will play as normal now.
$(".toggle-audio").on('click', function(event) {
audioPlaying = !audioPlaying;
$("#background-audio").remove();
clearInterval(backgroundAudio);
if (audioPlaying){
$(".audio1").play();
// play audio
}
else {
$(".audio1").pause();
}
And now make sure to hide these <audio> and <embed> elements
audio, embed {
position: absolute;
z-index: -9999;
}
Note: diplay: none and visibility: hidden will make the <embed> element not work.
There is a really neat trick to use the autoplay-function of the audio tag in chrome.
Add
<iframe src="silence.mp3" allow="autoplay" id="audio"></iframe>
whereas silence.mp3 only is 0.5 seconds of silence.
This
<audio id="player" autoplay controls><source src="0.mp3" type="audio/mp3"></audio>
works afterwards.
Chrome notices that a sound has been played and gives the permission for autoplay in audio tags.
As of April 2018, Chrome's autoplay policies changed:
"Chrome's autoplay policies are simple:
Muted autoplay is always allowed.
Autoplay with sound is allowed if:
User has interacted with the domain (click, tap, etc.).
On desktop, the user's Media Engagement Index threshold has been
crossed, meaning the user has previously play video with sound.
On mobile, the user has added the site to his or her home screen.
Also
Top frames can delegate autoplay permission to their iframes to allow
autoplay with sound.
"
Chrome's developer site has more information, including some programming examples, which can be found here: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
Just add this small script as depicted in https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio
<head>
<script>
window.onload = function() {
var context = new AudioContext();
}
</script>
</head>
Than this will work as you want:
<audio autoplay>
<source src="hal_9000_sorry_dave.mp3">
</audio>
At least you can use this:
document.addEventListener('click', musicPlay);
function musicPlay() {
document.getElementById('ID').play();
document.removeEventListener('click', musicPlay);
}
The music starts when the user clicks anywhere at the page.
It removes also instantly the EventListener, so if you use the audio controls the user can mute or pause it and the music doesn't start again when he clicks somewhere else..
The browsers have changed their privacy to autoplay video or audio due to Ads which is annoying. So you can just trick with below code.
You can put any silent audio in the iframe.
<iframe src="youraudiofile.mp3" type="audio/mp3" allow="autoplay" id="audio" style="display:none"></iframe>
<audio autoplay>
<source src="youraudiofile.mp3" type="audio/mp3">
</audio>
Just add an invisible iframe with an .mp3 as its source and allow="autoplay" before the audio element. As a result, the browser is tricked into starting any subsequent audio file. Or autoplay a video that isn’t muted.
You may simply use (.autoplay = true;) as following (tested on Chrome Desktop):
<audio id="audioID" loop> <source src="path/audio.mp3" type="audio/mp3"></audio>
<script>
var myaudio = document.getElementById("audioID").autoplay = true;
</script>
If you need to add stop/play buttons:
<button onclick="play()" type="button">playbutton</button>
<button onclick="stop()" type="button">stopbutton</button>
<audio id="audioID" autoplay loop> <source src="path/audio.mp3" type="audio/mp3">
</audio>
<script>
var myaudio = document.getElementById("audioID");
function play() {
return myaudio.play();
};
function stop() {
return myaudio.pause();
};
</script>
If you want stop/play to be one single button:
<button onclick="PlayStop()" type="button">button</button>
<audio id="audioID" autoplay loop> <source src="path/audio.mp3" type="audio/mp3">
</audio>
<script>
var myaudio = document.getElementById("audioID");
function PlayStop() {
return myaudio.paused ? myaudio.play() : myaudio.pause();
};
</script>
If you want to display stop/play on the same button:
<button onclick="PlayStop()" type="button">Play</button>
<audio id="audioID" autoplay loop> <source src="path/audio.mp3" type="audio/mp3">
</audio>
<script>
var myaudio = document.getElementById("audioID");
function PlayStop() {
if (elem.innerText=="Play") {
elem.innerText = "Stop";
}
else {
elem.innerText = "Play";
}
return myaudio.paused ? myaudio.play() : myaudio.pause();
};`
</script>
In some browsers audio may doesn't work correctly, so as a trick try adding iframe before your code:
<iframe src="dummy.mp3" allow="autoplay" id="audio" style="display:none"></iframe>
<button onclick="PlayStop()" type="button">Play</button>
<audio id="audioID" autoplay loop> <source src="path/audio.mp3" type="audio/mp3">
</audio>
<script>
var myaudio = document.getElementById("audioID");
function button() {
if (elem.innerText=="Play") {
elem.innerText = "Stop";
}
else {
elem.innerText = "Play";
}
return myaudio.paused ? myaudio.play() : myaudio.pause();
};
</script>
On adress bar click site settings, or for copy this address (localhost) and select allow on Sound
chrome://settings/content/siteDetails?site=https%3A%2F%2Flocalhost
Since 2020 this is a browser-related setting and cannot be enabled by html-code. The autoplay is blocked by default on most browsers. Here is where you can find it:
Firefox : where to enable/disable autoplay
Chrome : where to enable/disable autoplay
[EDIT # Sep. 7, 2021]
Just received some downvotes few days ago and I guess I have to make it clear: this solution REQUIRES users to hover their mouse over the webpage to work. There's no way to play sound on chrome without user interaction as it's blocked on purpose. The internet is now filled with intimidating ads and no one wants their browser spamming sounds from ads whenever they visit a website.
[EDIT # Dec. 22, 2021] I was a clown by spreading misinformation
Turns out some folks didn't grasp an important point of this method. You MUST enclose all parts in the <body> section with a <div>, as states below in the original description. This will NOT work on jsfiddle as it uses an embedded <iframe> document, which is exactly what Chrome is supposed to block.
[EDIT # Dec. 24, 2021]
Turns out I was a clown. Chrome blocks autoplay whenever users land on a page under a domain different from the last page they visited. Here are some demo I made:
If you visit the autoplay demo through this link, it will work properly.
However, this direct link will not work as the target domain is different from this very page.
[Original]
If you're OK with enclosing the whole HTML <body> with a <div> tag, here is my solution, which works on Chrome 88.0.4324.104 (the latest version as of Jan., 23, 2021).
First, add the audio section along with a piece of script shown below at the start of <body> section:
<audio id="divAudio">
<source src="music.mp3" type="audio/mp3">
</audio>
<script>
var vAudio = document.getElementById("divAudio");
var hasInit = false;
function playMusic()
{
if(!hasInit)
{
hasInit = true;
vAudio.play();
}
}
</script>
Second, enclose your whole HTML <body> contents (excluding the inserted piece of code shown above) with a dummy section <div onmouseover="playMusic()">. If your HTML <body> contents are already enclosed by a global <div> section, then just add the onmouseover="playMusic()" tag in that <div>.
The solution works by triggering the playMusic() function by hovering over the webpage and tricks Chrome of "thinking" that the user has done something to play it. This solution also comes with the benefit that the piece of audio would only be played when the user is browsing that page.
You could use <iframe src="link/to/file.mp3" allow="autoplay">, if the origin has an autoplay permission. More info here.
i used pixi.js and pixi-sound.js to achieve the auto play in chrome and firefox.
<script>
PIXI.sound.Sound.from({
url: 'audios/tuto.mp3',
loop:true,
preload: true,
loaded: function(err, sound) {
sound.play();
document.querySelector("#paused").addEventListener('click', function() {
const paused = PIXI.sound.togglePauseAll();
this.className = this.className.replace(/\b(on|off)/g, '');
this.className += paused ? 'on' : 'off';
});
}
});
</script>
HTML:
<button class="btn1 btn-lg off" id="paused">
<span class="glyphicon glyphicon-pause off"></span>
<span class="glyphicon glyphicon-play on"></span>
</button>
it also works on mobile devices but user have to touch somewhere on the screen to trigger the sound.
Use iframe instead:
<iframe id="stream" src="YOUTSOURCEAUDIOORVIDEOHERE" frameborder="0"></iframe>
temp fix
$(document).on('click', "#buttonStarter", function(evt)
{
var context = new AudioContext();
document.getElementById('audioPlayer').play();
$("#buttonStarter").hide()
$("#Game").show()
});
Or use a custom player to trigger play
http://zohararad.github.io/audio5js/
Note : Autoplay will be renabled in 31 December
Solution without using iframe, or javascript:
<embed src="silence.mp3" type="audio/mp3" autostart="true" hidden="true">
<audio id="player" autoplay controls><source src="source/audio.mp3" type="audio/mp3"></audio>
With this solution, the open/save dialog of Internet Explorer is also avoided.
<embed src="http://deinesv.cf/silence.mp3" type="audio/mp3" autostart="true" hidden="true">
<audio id="player" autoplay controls><source src="https://freemusicarchive.org/file/music/ccCommunity/Mild_Wild/a_Alright_Okay_b_See_Through/Mild_Wild_-_Alright_Okay.mp3" type="audio/mp3"></audio>
I've been banging away at this today, and I just wanted to add a little curiosum that I discovered to the discussion.
Anyway, I've gone off of this:
<iframe src="silence.mp3" allow="autoplay" id="audio" style="display:none"></iframe>
<audio id="audio" autoplay>
<source src="helloworld.mp3">
</audio>
This:
<audio id="myAudio" src="helloworld.mp3"></audio>
<script type="text/javascript">
document.getElementById("myAudio").play();
</script>
And finally this, a "solution" that is somewhat out of bounds if you'd rather just generate your own thing (which we do):
<script src='https://code.responsivevoice.org/responsivevoice.js'></script>
<input onclick='responsiveVoice.speak("Hello World");' type='button' value='Play' />
The discovery I've made and also the truly funny (strange? odd? ridiculous?) part is that in the case of the former two, you can actually beat the system by giving f5 a proper pounding; if you hit refresh repetetively very rapidly (some 5-10 times ought to do the trick), the audio will autoplay and then it will play a few times upon a sigle refresh only to return to it's evil ways.
Fantastic!
In the announcement from Google it says that for media files to play "automatically", an interaction between the user and the site must have taken place. So the best "solution" that I've managed to come up with thus far is to add a button, rendering the playing of files less than automatic, but a lot more stable/reliable.
I thought I would add what I found that will work for our solution. We will be hosting a site in our domain and we can add that site to Chrome's settings to allow auto-play.
I understand why autoplay is usually a little onerous but in this case for our organization it made sense to allow it.
The location in Chrome to allow autoplay by URL is: chrome://settings/content/sound?search=sound
In development with ASP.NET Core MVC, I just added the word: Localhost and that got it working for me (*Note it needs to be added in the Chrome Browser Visual Studio opens automatically).
In your HTML file <audio src="/path/to/your/music.mp3" autoplay></audio> or this
<audio id="musicplayer" autoplay>
<source src="/path/to/your/music.mp3" />
</audio>
And in your js file just add this line of code:audioElement.play(); This will play your music!
Notice that browsers often provide various forms of autoplay blocking
I add controls attribute too tag audio, and simply hide it in CSS.
And all works fine in Chrome.
<audio autoplay loop controls id="playAudio">
<source src="audio/source.mp3">
</audio>
The video tag can play audio as well. Given the audio tag doesn't seem to be behaving as it should be, you can just use the video tag for audio:
<video autoplay muted id="audio1" src="your.mp3" type="audio/mp3">
Your browser does not support the <code>video</code> element.
</video>
<script>
unmuteButton.addEventListener('click', function()
{
if ( unmuteButton.innerHTML == "unmute" )
{
unmuteButton.innerHTML = "mute";
audio1.muted = false;
} else {
unmuteButton.innerHTML = "unmute";
audio1.muted = true;
}
});
</script>
This little trick worked for me. I used a video tag instead. Auto played the video as muted and set the muted property to false on the window's load event.
<video autoplay loop muted>
<source src="sample.mp3" />
</video>
<script>
window.onload = function () {
document.querySelector("video").muted = false;
};
</script>
Google changed their policies last month regarding auto-play inside Chrome. Please see this announcement.
They do, however, allow auto-play if you are embedding a video and it is muted. You can add the muted property and it should allow the video to start playing.
<video autoplay controls muted>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
The default HTML5 audio autoplay attribute is not working in chrome, but you can force audio autoplay using JavaScript. Try this:
document.getElementById('myAudio').play();
This works for me.
In mobile mp4 video not working, it display only img of video.
I don't know how this problem solve.Link is here
http://innovatoryinfotech.com/theme/Restora/index-video.html
This is my html.
<video id="video" class="slider-video" width="100%" preload="auto" loop autoplay style="visibility: visible; width: 100%;">
<source src="video/Sushi-361.mp4">
<source src="video/Sushi-361.webm" type="video/webm">
<source src="video/Sushi-361.ogv" type="video/ogg">
</video>
Please solve this problem.
i add this script
var video = document.getElementById('video');
video.addEventListener('click',function(){
video.play();
},false);
then it work when click in the img then video is start.
But how to start automatic video on mobile.
It's not "not working", it's just preload and autoplay disabled. In iOS Safari, you can't make video play until user explicitly start it.
Here is the official document description:
In Safari on iOS (for all devices, including iPad), where the user may be on a cellular network and be charged per data unit, preload and autoplay are disabled. No data is loaded until the user initiates it.
UPDATE: according to https://developers.google.com/web/updates/2016/07/autoplay, autoplay was disabled in some versions of Chrome on Android too. However, "muted autoplay" is supported by Chrome for Android as of version 53, and is supported by Safari on iOS 10 and later.
Thus, you can try to fix this issue by adding muted attribute (<video autoplay muted>). However, due to browser history, it won't work on all devices.
Normally to embed video into an HTML5 page I use the following:
<video poster="">
<source type="video/mp4; codecs="avc1.42E01E, mp4a.40.2"" src="video/demo.mp4"></source>
<source type="video/ogg; codecs="theora, vorbis"" src="video/demo.ogg"></source>
<source type="video/webm; codecs="vp8, vorbis"" src="video/demo.webm"></source>
</video>
I know, there is no flash fallback. In this situation I didn't need one but that is not the purpose of this question.
My question is how to embed video that can serve both mobile and desktop browsers? Lets say this demo video is somewhere in the range of 20MB. Using the canplaythrough like so:
var onCanPlay = function(event) {
initLoad = false;
video.controls = true;
sb.removeEvent(this, 'canplaythrough');
sb.removeEvent(this, 'load');
return false;
};
if(initLoad) {
video.play();
if(video.readyState !== 4) {
video.addEventListener('canplaythrough', onCanPlay, false);
video.addEventListener('load', onCanPlay, false); //add load event as well to avoid errors, sometimes 'canplaythrough' won't dispatch.
setTimeout(function(){
video.pause(); //block play so it buffers before playing
}, 1);
}
} else {
if(video.currentTime > 0 && video.paused == false) {
video.play();
}
}
Note: Ignore the sb in front of my event handlers. I implement a custom event handler on my frontend framework and I copied this directly from production code.
Is typically the way I handle loading the video enough so that it will play seamlessly back to the user. Which works fine, but on mobile...because its such a large video file it takes a long time to load and quite honestly ruins the experience.
Is the answer to present a mobile version and a desktop?
<video controls>
<source src="demo-small.webm" type="video/webm" media="all and (max-width:600px)">
<source src="demo.webm" type="video/webm">
</video>
I've read a few things about media queries being removed from spec and its got me rethinking if I am even serving video the right way at all. Maybe it would be better to somehow stream the video from the server and avoid the HTML5 tag altogether? If thats the case I could use some direction...
I have 2 recommendations for you. First take advantage of the pre-load attribute.
<video controls preload="auto" >
<source type="video/mp4; codecs="avc1.42E01E, mp4a.40.2"" src="video/demo.mp4"></source>
<source type="video/ogg; codecs="theora, vorbis"" src="video/demo.ogg"></source>
<source type="video/webm; codecs="vp8, vorbis"" src="video/demo.webm"></source>
Preload will load a percentage of the video as soon as the video tag is rendered.
You may or may not be aware that the poster image can break certain iOS devices and controls must be present for some iOS devices. Additionally, mp4 must be first which you did have, but I am just noting it, because surprise! iOS devices need it first. If you have an html5 version that meets all of this criteria but still does not play on---- iOS devices look into the framerate, the size, and bitrates, baseline or standards profiles, etc. iOS is a picky little POS.
Secondly if you have control over the render of the video file be sure to set key frames every 10 secs or so depending on the length of the movie. This can create several concurrent streams or downloads rather than one. Target bitrate of .8 - 1.6 for SD or smaller video, 1.4 - 2.8 for HD usually works to keep quality and speed without sacrificing too much.