我应该如何使用用户的iTunes音乐在我的应用中播放AVPlayer视频?

时间:2017-01-16 09:42:42

标签: ios swift swift3 avplayer

我有一个没有音乐的视频,即使在另一个应用中播放音乐,我也希望向用户显示。如果播放音乐,我的下面代码会中断视频播放。

在视图控制器中:

    if let filePath = Bundle.main.path(forResource: "streamVideo", ofType: "mp4") {

        print("handled video: \(filePath)")
        let videoURL = NSURL(fileURLWithPath: filePath)
        avPlayer = AVPlayer(url: videoURL as URL)

        avPlayerLayer = AVPlayerLayer(player: avPlayer)
        avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
        avPlayer.volume = 0
        avPlayer.actionAtItemEnd = AVPlayerActionAtItemEnd.none

        avPlayerLayer.frame = view.layer.bounds
        view.backgroundColor = UIColor.clear;
        view.layer.insertSublayer(avPlayerLayer, at: 0)

        NotificationCenter.default.addObserver(self,
                                               selector: #selector(FirstVC.playerItemDidReachEnd),
                                               name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                               object: avPlayer.currentItem)

        avPlayer.play()

    }

在app delegate:

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
    } catch let error as NSError {
        print(error)
    }

    do {
        try AVAudioSession.sharedInstance().setActive(true)
    } catch let error as NSError {
        print(error)
    }

0 个答案:

没有答案