![](/img/trans.png)
[英]Swift background music that pauses when apple music/ spotify is playing in background
[英]Music not playing when app is in the background Swift Xcode
我已經編寫了這段代碼來在我的應用程序運行時播放音樂,但是當我轉到另一個應用程序時,音樂就會停止。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.