如何在Swift 2 / AVPlayer中恢复背景音频? [英] How to resume background audio in Swift 2 / AVPlayer?
本文介绍了如何在Swift 2 / AVPlayer中恢复背景音频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习Swift作为我的第一门编程语言。
I am learning Swift as my first programming language.
我在中断后努力了很长时间恢复背景音频播放例如致电)
I've struggled for many hours to resume background audio playback after interruption (eg call)
会发生什么:
- 当应用程序转到后台时,音频会继续播放(正常)
- 当被通话中断时,获取中断通知开始
(正常) - 当通话结束时,获取中断通知
结束(正常) - 继续播放音频(不起作用 - 听不见)
- Audio keeps playing when app goes to background (works)
- When interrupted by a call, get the notification for interruption began (works)
- When call ends, get the notification for interruption ends (works)
- Resume playing the audio (does NOT work - hear nothing)
非常感谢任何帮助!谢谢
Really appreciate any help! Thanks
注意:
- 该应用是
- 我已经尝试过没有时间延迟恢复播放 - 两种方式都没有工作
$ b $注册后台音频并在中断前播放正常b
代码:
Code:
import UIKit
import AVFoundation
var player: AVQueuePlayer!
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true, withOptions: .NotifyOthersOnDeactivation)
} catch { }
let songNames = ["music"]
let songs = songNames.map { AVPlayerItem(URL:
NSBundle.mainBundle().URLForResource($0, withExtension: "mp3")!) }
player = AVQueuePlayer(items: songs)
let theSession = AVAudioSession.sharedInstance()
NSNotificationCenter.defaultCenter().addObserver(self,
selector:"playInterrupt:",
name:AVAudioSessionInterruptionNotification,
object: theSession)
player.play()
}
func playInterrupt(notification: NSNotification) {
if notification.name == AVAudioSessionInterruptionNotification
&& notification.userInfo != nil {
var info = notification.userInfo!
var intValue: UInt = 0
(info[AVAudioSessionInterruptionTypeKey] as! NSValue).getValue(&intValue)
if let type = AVAudioSessionInterruptionType(rawValue: intValue) {
switch type {
case .Began:
print("aaaaarrrrgggg you stole me")
player.pause()
case .Ended:
let timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "resumeNow:", userInfo: nil, repeats: false)
}
}
}
}
func resumeNow(timer : NSTimer) {
player.play()
print("attempted restart")
}
}
推荐答案
终于搞定了!
解决方案:添加了通过将setCategory行更改为可混合选项:
Solution: added the mixable option by changing the setCategory line to be:
AVAudioSession.sharedInstance()。 setCategory(AVAudioSessionCategoryPlayback,withOptions:AVAudioSessionCategoryOptions.MixWithOthers)
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers )
这篇关于如何在Swift 2 / AVPlayer中恢复背景音频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文