如何用swift 2.0播放背景音乐?

我是swift和ios开发的新手。 我的代码一直在运行,直到我更新到Swift 2.0,我使用了swift迁移工具,但我仍然无法弄清楚如何对代码进行排序和修复。 请帮忙!

import AVFoundation var backgroundMusicP: AVAudioPlayer! func playBackgroundMusic(filename: String) { let url = NSBundle.mainBundle().URLForResource( filename, withExtension: nil) if (url == nil) { print("Could not find file: \(filename)") return } var error: NSError? do { backgroundMusicP = try AVAudioPlayer(contentsOfURL: url!) } catch { backgroundMusicP == nil } if backgroundMusicP == nil { print("Could not create audio player: \(error)") return } backgroundMusicP.numberOfLoops = -1 backgroundMusicP.prepareToPlay() backgroundMusicP.play() } 

更新了swift 2.0的function:

 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) } } 

用这种方式:

 playBackgroundMusic("yourFileName.mp3") 

您还可以启用会话以进行后台播放function。

 func enableBackgroundPlaying(_ enable: Bool) throws { do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) do { try AVAudioSession.sharedInstance().setActive(enable) } catch { throw error } } catch { throw error } }