1

最近我在使用 Xcode (7.0) 的 beta 版本时遇到了一个问题。我无法听到通过此代码播放的声音:(它是 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()
}

}
4

1 回答 1

9

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

试试这样:

class ViewController: UIViewController {

    var backMusic: AVAudioPlayer!
    // ...
    @IBAction func buttonTouchUpInside(sender: AnyObject) {
        backMusic = setupAudioPlayerWithFile("sound", type: "wav")
        backMusic.play()
    }
}
于 2015-06-16T16:31:28.000 回答