音频不在模拟器中播放

Audio not playing in simulator

我有三个按钮,我试图让每个按钮都能播放声音。

声音无法在模拟器上播放,想知道我的代码出了什么问题。

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")
          }
     }

 }

你应该将 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")
        }
    }