walton
walton

Reputation: 121

Audio not playing in simulator

I have three buttons and I'm trying to get a sound to play with each button.

The sounds don't play on the simulator wondering what was going wrong in my code.

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

 }

Upvotes: 1

Views: 578

Answers (1)

HardikDG
HardikDG

Reputation: 6122

You should make AVAudioPlayer as global variable as local variable of 'AVAudioPlayer' get deallocate before it plays, your code can like this

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

Upvotes: 4

Related Questions