Sim*_*ead 9 audio avfoundation ios avplayer swift
我正在学习Swift作为我的第一门编程语言.
中断后我已经挣了好几个小时才恢复背景音频播放(例如通话)
会发生什么:
非常感谢任何帮助!谢谢
笔记:
码:
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")
}
}
Run Code Online (Sandbox Code Playgroud)
终于明白了!
解决方案:通过将setCategory行更改为添加了mixable选项:
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback,
withOptions: .mixWithOthers )
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6249 次 |
最近记录: |