iOS Swift 2.0 - AvAudioPlayer 没有播放任何声音

iOS Swift 2.0 - AvAudioPlayer is not playing any sound

最近我在使用 Xcode (7.0) 的测试版时遇到了 运行 问题。 我听不到我通过这段代码播放的声音: (是Main.storyboard的一个ViewController,有一个按钮连接到buttonTouchUpInside()

import UIKit
import AVFoundation

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
}

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

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!
}

@IBAction func buttonTouchUpInside(sender: AnyObject) {
    let backMusic = setupAudioPlayerWithFile("sound", type: "wav")
    backMusic.play()
}

}

您只需将 backMusic 的声明移出您的 IBAction:

这样试试:

class ViewController: UIViewController {

    var backMusic: AVAudioPlayer!
    // ...
    @IBAction func buttonTouchUpInside(sender: AnyObject) {
        backMusic = setupAudioPlayerWithFile("sound", type: "wav")
        backMusic.play()
    }
}