codegeek511 codegeek511 - 6 months ago 29
Swift Question

Getting a fatal error when trying to play sound in Swift

I have worked my way through this tutorial here. One of the last things you do is have a button make sound when it is pressed. I wanted to then continue using that same logic to make a sound board app. However when I stripped the non-essential parts besides it making noise inside a new project I started getting a fatal error.

Here is my ViewController.swfit file:

import UIKit
import AVFoundation



class ViewController: UIViewController {

var sample : AVAudioPlayer?

func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer? {
//1
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
let url = NSURL.fileURLWithPath(path!)

//2
var audioPlayer:AVAudioPlayer?

// 3
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: url)
} catch {
print("Player not available")
}

return audioPlayer
}

override func viewDidLoad() {
super.viewDidLoad()

if let sample = self.setupAudioPlayerWithFile("Stomach", type:"aif") {
self.sample = sample
}
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@IBAction func buttonPressed() {
sample?.play()
}


}


Here is my project when the fatal error hits

enter image description here

I have also tried this solution but I got errors as well.

I am running on El Capitan 10.11.3 with Xcode 7.3

Answer

Have you included the an audio file named "Stomach.aif" in your project? If not, pathForResource will return nil and you'll crash when attempting to force unwrap that path. You can use a safer version of this function, although if it can't locate that file it still won't play the audio On the bright side it shouldn't crash.

func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer?  {
    var audioPlayer:AVAudioPlayer? = nil

    if let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String) {
        let url = NSURL.fileURLWithPath(path)

        do {
            try audioPlayer = AVAudioPlayer(contentsOfURL: url)
        } catch {
            print("Player not available")
        }
    }

    return audioPlayer
}