Swift - AVAudioPlayer不起作用

时间:2015-04-05 11:20:57

标签: ios swift audio avaudioplayer

我试图通过以下方式在iOS应用程序中播放我的aiff文件:

var sound = NSBundle.mainBundle().pathForResource("tropical_birds", ofType: "aiff")
var soundData = NSData(contentsOfFile: sound!)
let audioPlayer = AVAudioPlayer(data: soundData, error: nil)
audioPlayer.prepareToPlay()
audioPlayer.play()

1 个答案:

答案 0 :(得分:7)

您的AVAudioPlayer超出范围并被取消分配。将它分配给类的实例变量以延长其寿命。

e.g。

self.audioPlayer = AVAudioPlayer(data: soundData, error: nil)
self.audioPlayer.prepareToPlay()
self.audioPlayer.play()