我正在为我的应用程序使用AVAudioPlayer,当视图控制器加载时,视频加载时会自动播放音频,但如果音频无法找到该文件以及何时无法找到我想要的文件,我该怎么做声明?弹出警告信息,说无法找到音频。
代码:
var euphoriaAudio = try! AVAudioPlayer(contentsOfURL:
NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Euphoria", ofType: "mp3")!))
注意:此变量声明不在任何函数中。它独自坐在课堂上,完美无缺。
答案 0 :(得分:1)
应该做你描述的一切。
class EuphoriaViewController: UIViewController {
var player: AVAudioPlayer?
private func showAlert(message: String) {
let alert = UIAlertController(title: "Warning",
message: message,
preferredStyle: .Alert)
let ok = UIAlertAction(title: "OK", style: .Default) { action in
// Execute some code upon OK tap here if you'd like
}
alert.addAction(ok)
presentViewController(alert, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
guard let fileURL = NSBundle.mainBundle().URLForResource("Euphoria",withExtension: "mp3") else {
showAlert("Can't find Euphoria.mp3 resource")
return
}
do {
player = try AVAudioPlayer(contentsOfURL: fileURL)
player?.prepareToPlay()
}
catch {
showAlert("Can't load Euphoria.mp3 resource")
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
player?.play()
}
}
下次,亲自尝试并发布类似的问题 - 我这样做了,但它不起作用,这里是代码,......
如果您不知道如何显示提醒,...您应该从Start developing iOS Apps Today,About iOS App Architecture,iOS HIG开始......
此外,您应该阅读How do I ask a good question以便日后回答您的问题。到目前为止,你有10个问题,其中一些问题已经回答,其中3个问题已经接受了答案,......试着提出更好的问题......