iOS tutorial 12:視頻背景

參考:BackgroundVideoiOS

  • 新建項(xiàng)目 BackgroundVideoDemo
  • 新建BackgroundVideo.swift文件:
import Foundation
import AVKit
import AVFoundation

enum BackgroundVideoErrors: Error {
    case invalidVideo
}

class BackgroundVideo {
    
    var isMuted = true
    
    private var player : AVPlayer?
    private var videoURL: URL?
    private var viewController: UIViewController?
    private var hasBeenUsed: Bool = false
    
    
    
    init (on viewController: UIViewController, withVideoURL URL: String) {
        self.viewController = viewController
        
        // parse the video string to split it into name and extension
        let videoNameAndExtension:[String]? = URL.characters.split{$0 == "."}.map(String.init)
        if videoNameAndExtension!.count == 2 {
            if let videoName = videoNameAndExtension?[0] , let videoExtension = videoNameAndExtension?[1] {
                if let url = Bundle.main.url(forResource: videoName, withExtension: videoExtension) {
                    self.videoURL = url
                    // initialize our player with our fetched video url
                    self.player = AVPlayer(url: self.videoURL!)
                } else {
                    print(BackgroundVideoErrors.invalidVideo)
                }
            }
        } else {
            print("Wrong video name format")
        }
    }
    
    
    deinit{
        
        if self.hasBeenUsed {
            NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: nil)
            NotificationCenter.default.removeObserver(self, name: .UIApplicationWillEnterForeground, object: nil)
        }
        
    }
    
    
    public func setUpBackground(){
        self.player?.actionAtItemEnd = .none
        self.player?.isMuted = isMuted
        
        //add the video to your view ..
        let loginView: UIView = self.viewController!.view//get our view controllers view
        let playerLayer = AVPlayerLayer(player: self.player)
        playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill // preserve aspect ratio and resize to fill screen
        playerLayer.zPosition = -1 // set it's possition behined anything in our view
        playerLayer.frame = loginView.frame // set our player frame to our view's frame
        loginView.layer.addSublayer(playerLayer)
        
        
        
        // prevent video from disturbing audio services from other apps
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
            
        }
        catch {
            print("failed setting AVAudioSession Category to AVAudioSessionCategoryAmbient")
        }
        
        self.player?.play() // start the video
        
        /// 向通知中心發(fā)送視頻結(jié)束后再次從頭播放
        NotificationCenter.default.addObserver(self, selector: #selector(self.loopVideo), name: .AVPlayerItemDidPlayToEndTime, object: nil)
        // 視頻進(jìn)入Foreground后從頭播放
        NotificationCenter.default.addObserver(self, selector: #selector(self.loopVideo), name: .UIApplicationWillEnterForeground, object: nil)
        self.hasBeenUsed = true
        
    }
    
    // 循環(huán)播放視頻
    @objc private func loopVideo() {
        self.player?.seek(to: kCMTimeZero)
        self.player?.play()
    }
    
}
  • 在所需要的視圖控制器中定義變量var backgroundPlayer : BackgroundVideo?,然后再在viewDidLoad中定義:
   override func viewDidLoad() {
       super.viewDidLoad()

       let backgroundPlayer = BackgroundVideo(on: self, withVideoURL: "test.mp4")
       //是否打開靜音
//        backgroundPlayer?.isMuted = false
       
       backgroundPlayer.setUpBackground()

   }

詳細(xì)代碼: BackgroundVideoDemo

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市娇斑,隨后出現(xiàn)的幾起案子颠悬,更是在濱河造成了極大的恐慌,老刑警劉巖眼俊,帶你破解...
    沈念sama閱讀 216,591評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件厢漩,死亡現(xiàn)場(chǎng)離奇詭異待错,居然都是意外死亡褐澎,警方通過查閱死者的電腦和手機(jī)会钝,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來工三,“玉大人迁酸,你說我怎么就攤上這事〖笳” “怎么了奸鬓?”我有些...
    開封第一講書人閱讀 162,823評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)掸读。 經(jīng)常有香客問我串远,道長(zhǎng),這世上最難降的妖魔是什么儿惫? 我笑而不...
    開封第一講書人閱讀 58,204評(píng)論 1 292
  • 正文 為了忘掉前任澡罚,我火速辦了婚禮,結(jié)果婚禮上姥闪,老公的妹妹穿的比我還像新娘。我一直安慰自己砌烁,他們只是感情好筐喳,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,228評(píng)論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著函喉,像睡著了一般避归。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上管呵,一...
    開封第一講書人閱讀 51,190評(píng)論 1 299
  • 那天梳毙,我揣著相機(jī)與錄音,去河邊找鬼捐下。 笑死账锹,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的坷襟。 我是一名探鬼主播奸柬,決...
    沈念sama閱讀 40,078評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼婴程!你這毒婦竟也來了廓奕?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,923評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎桌粉,沒想到半個(gè)月后蒸绩,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,334評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡铃肯,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,550評(píng)論 2 333
  • 正文 我和宋清朗相戀三年患亿,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片缘薛。...
    茶點(diǎn)故事閱讀 39,727評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡窍育,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出宴胧,到底是詐尸還是另有隱情漱抓,我是刑警寧澤,帶...
    沈念sama閱讀 35,428評(píng)論 5 343
  • 正文 年R本政府宣布恕齐,位于F島的核電站乞娄,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏显歧。R本人自食惡果不足惜仪或,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,022評(píng)論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望士骤。 院中可真熱鬧范删,春花似錦、人聲如沸拷肌。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)巨缘。三九已至添忘,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間若锁,已是汗流浹背搁骑。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留又固,地道東北人仲器。 一個(gè)月前我還...
    沈念sama閱讀 47,734評(píng)論 2 368
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像仰冠,于是被迫代替她去往敵國(guó)和親娄周。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,619評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容