AVAudioPlayer播放一个mp3文件时,居然没有声音。mp3文件是放在工程里面的,路径没有错误但就是死活没有声音。
func playSound() { let notifyUrl = NSBundle.mainBundle().pathForResource("notify", ofType: "mp3") //let notifyUrl = NSBundle.mainBundle().resourcePath?.stringByAppendingPathComponent("notify.mp3") if let mp3 = notifyUrl { let url = NSURL(fileURLWithPath: mp3) // var filemanager = NSFileManager() // let result = filemanager.fileExistsAtPath(mp3) // println("result=\(result)") AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil) var error:NSError? var avAudioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error) if error != nil { println(error) } else { avAudioPlayer.volume = 1.0 avAudioPlayer.prepareToPlay() avAudioPlayer.play() } } }
解决方法是把avAudioPlayer定义为全局变量的时候就有声音了,是不是很神奇。应该是被内存回收了所以没有声音,记得要定义为全局变量
var avAudioPlayer:AVAudioPlayer? func playSound() { let notifyUrl = NSBundle.mainBundle().pathForResource("notify", ofType: "mp3") //let notifyUrl = NSBundle.mainBundle().resourcePath?.stringByAppendingPathComponent("notify.mp3") if let mp3 = notifyUrl { let url = NSURL(fileURLWithPath: mp3) // var filemanager = NSFileManager() // let result = filemanager.fileExistsAtPath(mp3) // println("result=\(result)") AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil) var error:NSError? //var avAudioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error) avAudioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error) if error != nil { println(error) } else { avAudioPlayer?.volume = 1.0 avAudioPlayer?.prepareToPlay() avAudioPlayer?.play() } } }