声音 AVAudioPlayer 不工作

Sound AVAudioPlayer not working

我正在尝试创建一个使用声音的简单应用程序。我的 AVAudioPlayer 函数出现错误。

我的意思是:

import UIKit
import AVFoundation

class ViewController: UIViewController{
   var audioPlayer = AVAudioPlayer()

override func viewDidLoad() {
   super.viewDidLoad()

   var playSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Bell", ofType: "mp3"))

   audioPlayer = AVAudioPlayer(contentsOfURL: playSound, error: &error)

   audioPlayer.play()

}

尝试创建一个单独的函数。 试试这个..

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

    do {
        try audioPlayer = AVAudioPlayer(contentsOfURL: url)
    } catch {
        print("NO AUDIO PLAYER")
    }

    return audioPlayer!
}

然后 运行 audioPlayer.play() 随心所欲。