2016-02-05 42 views
17

目标是在没有控件的情况下在UIView中播放视频文件(* .mp4)。如何在不带控件的UIView内播放视频,如背景/墙纸?

它将用作ViewController和其他控件的背景/墙纸,即tableview,文本字段,图像将在视频播放的视图上显示。

有什么更好的方法来做到这一点? 谢谢

+0

是使用URL的本地视频还是You Tube视频? – Vidhyanand

+0

它将本地文件导入到项目中。其实会有几个文件(视频),每个单独的ViewController –

+0

请参阅http://stackoverflow.com/questions/17922017/display-video-inside-the-uiwebview-not-in-device-full-screen – Vidhyanand

回答

38

我已经达到了目标与本地AVPlayer

1.适用AVFoundation:

#import <AVFoundation/AVFoundation.h> 

2.Used供玩家属性:

@property (nonatomic) AVPlayer *avPlayer; 

3.Added视频文件转换为“视频”文件夹并将“视频”添加到项目中

4.Initialized玩家

NSString *filepath = [[NSBundle mainBundle] pathForResource:@"shutterstock_v885172.mp4" ofType:nil inDirectory:@"Video"]; 
NSURL *fileURL = [NSURL fileURLWithPath:filepath]; 
self.avPlayer = [AVPlayer playerWithURL:fileURL]; 
self.avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone; 

AVPlayerLayer *videoLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer]; 
videoLayer.frame = self.view.bounds; 
videoLayer.videoGravity = AVLayerVideoGravityResizeAspectFill; 
[self.view.layer addSublayer:videoLayer]; 

[self.avPlayer play]; 

5.Subscribed事件 - 视频并播放到结束

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:[self.avPlayer currentItem]]; 

6.Resumed视频从一开始就在相关的方法打

- (void)itemDidFinishPlaying:(NSNotification *)notification { 
    AVPlayerItem *player = [notification object]; 
    [player seekToTime:kCMTimeZero]; 
} 
1

Swift

在Swift中是类似的。将视频添加到您的资源包。我更完整的答案是here

import UIKit 
import AVFoundation 

class ViewController: UIViewController { 

    var player: AVPlayer? 

    @IBOutlet weak var videoViewContainer: UIView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     initializeVideoPlayerWithVideo() 
    } 

    func initializeVideoPlayerWithVideo() { 

     // get the path string for the video from assets 
     let videoString:String? = Bundle.main.path(forResource: "SampleVideo_360x240_1mb", ofType: "mp4") 
     guard let unwrappedVideoPath = videoString else {return} 

     // convert the path string to a url 
     let videoUrl = URL(fileURLWithPath: unwrappedVideoPath) 

     // initialize the video player with the url 
     self.player = AVPlayer(url: videoUrl) 

     // create a video layer for the player 
     let layer: AVPlayerLayer = AVPlayerLayer(player: player) 

     // make the layer the same size as the container view 
     layer.frame = videoViewContainer.bounds 

     // make the video fill the layer as much as possible while keeping its aspect size 
     layer.videoGravity = AVLayerVideoGravity.resizeAspectFill 

     // add the layer to the container view 
     videoViewContainer.layer.addSublayer(layer) 
    } 

    @IBAction func playVideoButtonTapped(_ sender: UIButton) { 
     // play the video if the player is initialized 
     player?.play() 
    } 
}