Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 651
  • Last Modified:

Autoplay video in mobile device

Is there a hack to auto play mp4 video in mobile device.  It seems as if this functionality is turned off in mobile devices but I am looking for a script/hack to over rife it.
0
rgranlund
Asked:
rgranlund
  • 2
1 Solution
 
leakim971PluritechnicianCommented:
you mean, people open a web page and you play the mp4 on their mobile phone right ?
0
 
Marco GasiFreelancerCommented:
Unfortunately, many browsers in mobiles have disabled autoplay function: play() method can only be iniitiated by user gesture.
What you can do is to add an event listener to some event. For instance I attached it to window touchstart using MediaElement.js:
		<script>
			$(document).ready(function () {
				var player = new MediaElementPlayer('#ID-OF-AUDIO-OR-VIDEO-TAG');
				player.load();
				window.addEventListener('touchstart', function audioStart() {
					player.play();
					this.removeEventListener('touchstart', audioStart);
				});
			});
		</script>

Open in new window

0
 
Marco GasiFreelancerCommented:
But I've just read in my console this message:
Performing operations that require explicit user interaction on touchstart events is deprecated and will be removed in M54, around October 2016. See https://www.chromestatus.com/features/5649871251963904 for more details.
So, it looks like Google doesn't want allow us to get play() working ecept the user don't explicitely tap on play button.
You can, if you want to increase the probability the audio/video start, using something like this:
			$(document).ready(function () {
				var player = new MediaElementPlayer('#player2');
				var playerPlaying = false;
				player.load();
				$('body').on('click', function () {
					if (playerPlaying) {
						player.pause();
						playerPlaying = false;
					} else {
						player.play();
						playerPlaying = true;
					}
				});
				window.addEventListener('touchstart', function audioStart() {
					player.play();
					this.removeEventListener('touchstart', audioStart);
					playerPlaying = true;
				});
			});
		</script>

Open in new window

This ensure that if user taps everywhere, the media starts playing. In addition, touchstart and body click will work together, at least until Chrome wont remove touchstart ability to trigger events whih require user gesture.
0

Featured Post

Threat Trends for MSPs to Watch

See the findings.
Despite its humble beginnings, phishing has come a long way since those first crudely constructed emails. Today, phishing sites can appear and disappear in the length of a coffee break, and it takes more than a little know-how to keep your clients secure.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now