rv7*_*284 5 ios avplayer swift
首先,我不是问如何在后台播放AVPlayer。有很多解决方案。我的问题有点不同。
我的应用程序中的 AVPlayer 正在播放“AVPlayerItem”数组。当最后一首歌完成后,我从第一首歌曲开始播放。当应用程序处于活动状态时,这完全可以正常工作,但是,如果在播放歌曲时按下主页按钮,最后一首歌曲就会在后台播放完毕。现在播放器停在这里,不再开始第一首歌曲。
知道为什么会出现这种行为以及解决方案是什么。
然后,按照:
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
print("AVAudioSession is Active")
} catch let error as NSError {
print(error.localizedDescription)
}
} catch let error as NSError {
print(error.localizedDescription)
}
Run Code Online (Sandbox Code Playgroud)
另外,要播放音频:
var backgroundMusicPlayer = AVAudioPlayer()
func playBackgroundMusic(filename: String) {
let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
guard let newURL = url else {
print("Could not find file: \(filename)")
return
}
do {
backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: newURL)
backgroundMusicPlayer.numberOfLoops = -1
backgroundMusicPlayer.prepareToPlay()
backgroundMusicPlayer.play()
} catch let error as NSError {
print(error.description)
}
}
Run Code Online (Sandbox Code Playgroud)
那么,主要是:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.becomeFirstResponder()
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
}
Run Code Online (Sandbox Code Playgroud)
在 AppDelegate 的 Final 中,您将在以下位置收到事件:
override func remoteControlReceivedWithEvent(event: UIEvent?) {
let rc = event!.subtype
print("does this work? \(rc.rawValue)")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1430 次 |
| 最近记录: |