我只是在点击按钮时尝试播放音频,但是这行代码出错了。
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) {
}
}
错误是
调用中的参数标签不正确(包含'contentsOfURL:错误:',期望'contentsOfURL:fileTypeHint:')。
当我将错误更改为fileTypeHint时,它仍然无效。
答案 0 :(得分:3)
您需要通过将该行更改为
来使用新的Swift 2语法ButtonAudioPlayer = try! AVAudioPlayer(contentsOfURL: ButtonAudioURL)
答案 1 :(得分:1)
AVAudioPlayer类可能会抛出错误,您需要考虑这一点。我个人更喜欢do语句,它提供了捕获和处理错误的机会。
这段代码对我来说很好:
import UIKit
import AVFoundation
class ViewController: UIViewController {
let ButtonAudioURL = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource("test", ofType: "mp3")!)
let ButtonAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
do {
ButtonAudioPlayer = try AVAudioPlayer(contentsOfURL: ButtonAudioURL, fileTypeHint: ".mp3")
ButtonAudioPlayer.play()
} catch let error {
print("error loading audio: Error: \(error)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
您也可以将其设为可选项,如下所示:
ButtonAudioPlayer = try AVAudioPlayer(contentsOfURL: ButtonAudioURL, fileTypeHint: ".mp3")
ButtonAudioPlayer?.play()
使用此方法,如果前一个语句中没有引发错误,它将只尝试播放该文件,但会阻止运行时错误。