Ios AVAudioPlayer可以';在使用调试脚本之前,不要播放声音
我在iOS 9上使用Xcode 7.3.1,在AVAudioPlayer上播放声音时遇到问题。我已经尝试了所有可能的解决方案,但我的代码没有任何效果Ios AVAudioPlayer可以';在使用调试脚本之前,不要播放声音,ios,swift,audio,avaudioplayer,Ios,Swift,Audio,Avaudioplayer,我在iOS 9上使用Xcode 7.3.1,在AVAudioPlayer上播放声音时遇到问题。我已经尝试了所有可能的解决方案,但我的代码没有任何效果 let mp3Url = NSBundle.mainBundle().URLForResource("BCA", withExtension:"mp3")! var player = AVAudioPlayer() do { player = try AVAudioPlay
let mp3Url = NSBundle.mainBundle().URLForResource("BCA", withExtension:"mp3")!
var player = AVAudioPlayer()
do {
player = try AVAudioPlayer(contentsOfURL: mp3Url)
player.prepareToPlay()
player.play()
} catch let error as NSError {
print(error.description)
}
在我将断点放在player.play()并使用po-player之前,声音不会播放。然后播放声音
任何想法都会对我有帮助 试试这个:
var player: AVAudioPlayer?
func playSound(){
guard let url = Bundle.main.url(forResource: "alert_song", withExtension: "mp3") else {
print("MP3 resource not found.")
return
}
print("Music to play : \(String(describing: url))")
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url)
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
试试这个:
var player = AVAudioPlayer() //global variables will otherwise be deadlock
let mp3Url = NSBundle.mainBundle().URLForResource("BCA", withExtension:"mp3")!
do {
player = try AVAudioPlayer(contentsOfURL: mp3Url)
player.play()
} catch let error as NSError {
print(error.description)
}
这对我有用!如果我使用player作为全局变量,那么就可以了