我有三个按钮,我正试着用每个按钮播放声音。
声音无法在模拟器上播放,想知道我的代码出了什么问题。
import UIKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func mmm_sound(sender: UIButton) {
playSound("mmm")
}
@IBAction func aww_sound(sender: UIButton) {
playSound("aww")
}
@IBAction func maniacal_sound(sender: UIButton) {
playSound("hah")
}
//sound function
func playSound(soundName: String)
{
let sound = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource(soundName, ofType: "wav")!)
do{
let audioPlayer = try AVAudioPlayer(contentsOfURL:sound)
audioPlayer.prepareToPlay()
audioPlayer.play()
}catch {
print("Error getting the audio file")
}
}
}
答案 0 :(得分:2)
你应该把AVAudioPlayer作为全局变量作为' AVAudioPlayer'的局部变量。在播放之前获得解除分配,您的代码可以像这样
//at top
var audioPlayer = AVAudioPlayer()
func playSound(soundName: String)
{
let sound = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource(soundName, ofType:"wav")!)
do{
audioPlayer = try AVAudioPlayer(contentsOfURL:sound)
audioPlayer.prepareToPlay()
audioPlayer.play()
}catch {
print("Error getting the audio file")
}
}