尝试在Swift中播放声音时出现致命错误

时间:2016-05-25 18:33:26

标签: xcode swift avaudioplayer

我已经完成了本教程here。你做的最后一件事就是按下按钮发出声音。我想继续使用相同的逻辑来制作声卡应用程序。然而,当我剥离非必要部件除了它在一个新项目内发出噪音我开始得到一个致命的错误。

这是我的ViewController.swfit文件:

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


}

当致命错误发生时,这是我的项目

enter image description here

我也试过这个solution,但我也遇到了错误。

我使用Xcode 7.3运行El Capitan 10.11.3

1 个答案:

答案 0 :(得分:2)

您是否在项目中添加了名为“Stomach.aif”的音频文件?如果没有,pathForResource将返回nil,并且在尝试强制打开该路径时您将崩溃。您可以使用此功能的更安全版本,但如果它无法找到该文件,它仍然无法播放音频。在光明的一面它不应该崩溃。

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
}
相关问题