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

Fre*_*tte 1 ios swift xcode7

最近我在使用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()
}

}
Run Code Online (Sandbox Code Playgroud)

Leo*_*bus 9

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

试试这样:

class ViewController: UIViewController {

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

  • 为了使Leo的解决方案更加清晰,您不能将AVAudioPlayer声明为局部变量,或者在退出该范围之前将其处理,然后才能播放任何内容. (2认同)