Autoplay HTML5 audio/video in iOS5

2020-02-10 10:15发布

问题:

I have an HTML5 web-app that has sound effects. I'm trying to get these effects working in iOS5 and can't for the life of me.

Wondering if anyone has any work-arounds to get JS control of an HTML5 audio/video control in iOS5.

Or even a way to control multiple audio files with one click. As it stands right now, if I have 10 sound effects, I'd need 10 user clicks to get control of all of them, which is absurd!

回答1:

Absurb, but you have to see it from iPhone or any mobile phone's point of view. It is a mobile phone going over a cellular network with bandwidth limitations, which many people know about from the recent Sprint commercial. They do not want users going over their bandwidth limit because some site is sending their phone a large amount of data without them taking action themselves.

The following is an excerpt from the official Safari Developer Library with more details.

User Control of Downloads Over Cellular Networks

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. This means the JavaScript play() and load() methods are also inactive until the user initiates playback, unless the play() or load() method is triggered by user action. In other words, a user-initiated Play button works, but an onLoad="play()" event does not.

This plays the movie: <input type="button" value="Play" onClick="document.myMovie.play()">

This does nothing on iOS: <body onLoad="document.myMovie.play()">



回答2:

Due to Apple, they have restricted the auto-play features to prevent cell data charges. In xcode4 i added a workaround though. In your "webViewDidFinishLoad" Send a javascript call to auto play the video and it works. I tried this in the html file with regular javascript but it did not work. Doing it through webViewDidFinishLoad did the trick though. In this example i want to auto play the video on my index.html page. I have a javascript function on that page called startVideo().

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSURLRequest* request = [webView request];
    NSString *page = [request.URL lastPathComponent];
    if ([page isEqualToString:@"index.html"]){
        NSString *js = @"startVideo();";
        [myWebMain stringByEvaluatingJavaScriptFromString:js];
    }
}

And here's my javascript function:

<script>
function startVideo(){
var pElement3 = document.getElementById('myVideo');
pElement3.play();
}
</script>

And here's the html in case you're new to html video

<video id="myVideo" poster="index_poster.png" width="1024" height="768" xcontrols     autoplay="autoplay">
<source src="flow.m4v" type="video/mp4"/>
browser not supports the video
</video>


回答3:

Have you tried something like this??

function clickedOnce(){
  $('audio').each(function(){
      this.play();
  });
}