目前我有两个几乎相同的功能,但只有一个功能正常,我无法弄清楚原因。
playSound()函数可以使用类的audioPlayer:AVAudioPlayer对象一次播放一个音频文件。
为了使我可以同时播放多个声音,我创建了一个名为playMySound()的新函数,它创建了自己的AVAudioPlayer实例,而不是使用类的audioPlayer:AVAudioPlayer对象。
奇怪的是,当我调用playSound()时声音播放正常,但是当我调用playMySound()时它没有播放。
以下是有效的代码:
var audioPlayer: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
audioPlayer = AVAudioPlayer()
}
func playSound(audioFileName: String) {
if let sound = NSDataAsset(name: audioFileName) {
do {
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try! AVAudioSession.sharedInstance().setActive(true)
try audioPlayer = AVAudioPlayer(data: sound.data)
audioPlayer.delegate = self
audioPlayer.play()
} catch {
print("Error playing sound: \(audioFileName)")
}
}
}
并且代码不起作用:
func playMySound(audioFileName: String) {
if let sound = NSDataAsset(name: audioFileName) {
do {
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try! AVAudioSession.sharedInstance().setActive(true)
var myAudioPlayer: AVAudioPlayer = AVAudioPlayer()
myAudioPlayer = try AVAudioPlayer(data: sound.data)
myAudioPlayer.delegate = self
// Calling prepareToPlay() doesn't seem to fix it
// myAudioPlayer.prepareToPlay()
print("Trying to play my audio player")
myAudioPlayer.play()
} catch {
print("Error playing sound: \(audioFileName)")
}
}
}
"尝试播放我的音频播放器"输出到控制台,所以它肯定贯穿整个函数,但由于某种原因调用myAudioPlayer.play()似乎无法正常工作。
有人可以帮忙吗?提前谢谢!