295
292

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

iPhone Safariで動画をインライン再生する方法

Last updated at Posted at 2016-03-29

##iPhone SafariのVideoタグの制限
iPhone SafariのVideoタグには大きく2つ制限がある。

  1. ユーザインタラクション(タップ)なしに再生できない
  2. 初期再生時必ずフルスクリーン再生になる

特に2がクセモノで、これのせいでモバイルブラウザに動画広告はほぼ無いし、モバイルブラウザゲームには動画演出がない(MotionJPEGみたいにjpegを数百枚数千枚差し替えるとか涙ぐましいことをしている例はある)。

##制限は超えられる
この制限が超えられないものかと調べてみると、やはり同じようなことを訊いている人が居た。

inline html5 video on iphone - Stack Overflow
http://stackoverflow.com/questions/30855662/inline-html5-video-on-iphone

で、そのベストアンサーが

It's very rough, but the basic gist is that you "seek" through the video instead of playing it outright. So instead of calling:
video.play()

You instead set a loop using request animation frame or setInterval, then set the:
video.currentTime = __FRAME_RATE__

つまり、

Playすんな、currentTimeを動かせ!

##Sample Code

ループ再生
	var video = document.createElement('video');
	video.style.display = 'none';
	document.body.appendChild(video);
	var canvas = document.getElementById('myCanvas');
	var ctx = canvas.getContext("2d");
	var ctime = 0;
	var lastTime;
    var ua = navigator.userAgent;
    if(/(iPhone|iPod)/.test(ua)) { // iPadもVideoはインライン再生可能である
        video.addEventListener('canplay',function(){
            lastTime = Date.now();
            setInterval(function(){
                var curTime = Date.now();
                var diff = Date.now() - lastTime;
                lastTime = curTime;
                ctime += diff/1000;
                video.currentTime = ctime;
                ctx.drawImage(video, 0, 0, 480, 360);
                if(video.duration <= video.currentTime){
                    ctime = 0;
                }
            }, 1000/30);
        },false);
    }else{
        video.addEventListener('canplay',function(){
            video.play();
            video.loop = true;
            setInterval(function(){
                ctx.drawImage(video, 0, 0, 480, 360);
            }, 1000/30);
        },false);
    }
	video.src = 'sample.mp4';
	video.load();

##DEMO
http://jsrun.it/hadakadenkyu/iFDV
http://jsrun.it/hadakadenkyu/iFDV

##One more thing
WebGLでもイケます

##音声は?
書いた

295
292
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
295
292

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?