【发布时间】:2016-07-20 11:59:15
【问题描述】:
我编写了这段代码来在我的应用程序运行时播放音乐,但是当我转到另一个应用程序时,音乐停止了。
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)
print("AVAudioSession is Active")
} catch let error as NSError {
print(error.localizedDescription)
}
} catch let error as NSError {
print(error.localizedDescription)
}
playBackgroundMusic("anti.mp3")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
import AVFoundation
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)
}
}
我还在所需背景模式下的 info.plist 中添加了音频字符串。
我也得到了这个输出,所以我认为它会在使用其他应用程序时继续在后台播放,但事实并非如此。
AVAudioSession Category Playback OK
AVAudioSession is Active
AVAudioSession Category Playback OK
AVAudioSession is Active
【问题讨论】: