2016-02-05 44 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() 
    } 
}