我只是想在点击按钮时播放音频,但是这行代码却出现错误。

ButtonAudioPlayer = AVAudioPlayer(contentsOfURL: ButtonAudioURL, error: nil)

这是我的整个代码:
import UIKit
import AVFoundation

class ViewController: UIViewController {

var ButtonAudioURL = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource("Audio File 1", ofType: "mp3")!)

var ButtonAudioPlayer = AVAudioPlayer()



override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    ButtonAudioPlayer = AVAudioPlayer(contentsOfURL: ButtonAudioURL, error:       nil)

}


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

@IBAction func playAudio1(sender: UIButton) {


}

}

错误是



当我将错误更改为fileTypeHint时,它仍然不起作用。

最佳答案

您需要使用新的Swift 2语法,方法是将该行更改为

ButtonAudioPlayer = try! AVAudioPlayer(contentsOfURL: ButtonAudioURL)

08-05 03:05