WebViewを使わずにnativeの機能で動画再生を実装した最小限のアプリ
iOSでnativeの機能の勉強をするために、動画再生の最小限の構成のアプリを実装します。
(WebViewのvideoタグではない実装をします。)
Xcodeで新規Project を作成
Xcodeを開き、File > new > Project から新規プロジェクトを作成。
iOS > Appを選択し、任意のプロジェクト名で作成します。
(今回自分はcordovaの既存pluginの勉強のためObjective-Cのプロジェクトを作成します。)
クラスを追加する操作(ヘッダーファイルとObjective-Cファイル)
プロジェクト名フォルダに、右クリック > New File から、ヘッダーファイルとObjective-Cファイルを追加し
それぞれ クラス名.h、クラス名.m という名前を付けます。
拡張子「.h」のヘッダーファイル にはクラスのインターフェースを、
拡張子「.m」のObject-Cファイル にはクラスの実装を記述します。
AVPlayerView の実装
UIView を継承した AVPlayerView を実装します。
LayerClassには、AVFoundationからAVPlayerLayer(AVPlayerを再生できるLayer)を指定します。
# import <UIKit/UIKit.h>
# import <AVFoundation/AVFoundation.h>
@interface AVPlayerView : UIView
@end
# import "AVPlayerView.h"
@implementation AVPlayerView
+ (Class) layerClass
{
return AVPlayerLayer.class;
}
@end
ViewController の実装
新規プロジェクト作成時に作られる、ViewControllerクラス(ViewController.h、ViewController.m)を書き換えます。
# import "AVPlayerView.h"
# import <UIKit/UIKit.h>
# import <AVFoundation/AVFoundation.h>
# import <AudioToolbox/AudioToolbox.h>
@interface ViewController : UIViewController;
# import "AVPlayerView.h"
# import "ViewController.h"
@interface ViewController () {
AVPlayer *player;
AVPlayerView *playerView;
}
@end
@implementation ViewController
-(void) viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self setupAVPlayerForURL:[NSURL URLWithString:@"任意のmp4ファイルにアクセスするURL"]];
[self startPlay];
}
-(void) startPlay {
//play
[player play];
}
-(void) setupAVPlayerForURL: (NSURL*) url {
// make asset data (AVAsset)
AVAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
//make AVPlayerItem from asset data
AVPlayerItem *anItem = [AVPlayerItem playerItemWithAsset:asset];
// make AVPlayer with AVPlayerItem and set to instance var, player
player = [AVPlayer playerWithPlayerItem:anItem];
// make AVPlayerView with full screen CGRect frame and set to instance var, playerView
playerView = [[AVPlayerView alloc] initWithFrame:CGRectMake(
0,
0,
self.view.frame.size.width, //same width with view frame size
self.view.frame.size.height //same height with view frame size
)];
// set player to playerView.layer
[(AVPlayerLayer*) playerView.layer setPlayer:player];
// set playerView as subview to self.view
[self.view addSubview:playerView];
// bring subview in front of self.view
[self.view bringSubviewToFront:playerView];
}
@end
アプリを実行
xcodeの上部の再生マークのボタンをクリックしてアプリケーションのビルドとエミュレータでのアプリの実行を行います。
URLで指定した動画が再生されます。
動画はNHKメディアライブラリーより使用しました。
https://www9.nhk.or.jp/das/movie/D0002160/D0002160757_00000_V_000.mp4
以上です。