我对编码很陌生,而且我试图在其他类似问题的答案中实现建议的代码,但没有运气。该应用程序构建正常,但每次我去播放实际的音频文件时,我收到一条错误消息说"致命错误:在解开一个可选值(lldb)"时意外地发现了nil;而它突出显示audioPlayer.play()
行。
有什么想法吗?
import UIKit
import AVFoundation
class PlaySoundsViewController: UIViewController {
var audioPlayer:AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
if let filePath = NSBundle.mainBundle().pathForResource("movie_quote", ofType: "mp3"),
let filePathURL = NSURL.fileURLWithPath(filePath) {
var audioPlayer = AVAudioPlayer(contentsOfURL: filePathURL, error: nil)
}else{
println("the filePath is empty OR the file did not load")
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func playSlowAudio(sender: UIButton) {
audioPlayer.play()
}
答案 0 :(得分:1)
以下是播放音频和停止音频的完整工作代码:
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate {
@IBOutlet weak var playAudio: UIButton!
@IBOutlet weak var stopAudio: UIButton!
var audioPlayer : AVAudioPlayer? = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL.fileURLWithPath(NSBundle.mainBundle().pathForResource("we_cant_Stop", ofType: "mp3")!)
var error : NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
if let err = error{
println("audioPlayer error \(err.localizedDescription)")
}else{
audioPlayer?.delegate = self
audioPlayer?.prepareToPlay()
}
}
@IBAction func playTapped(sender: AnyObject) {
if let player = audioPlayer{
player.play()
}
}
@IBAction func stopTapped(sender: AnyObject) {
if let player = audioPlayer {
player.stop()
}
}
}
希望它会有所帮助。
检查THIS示例项目以获取更多信息。
答案 1 :(得分:0)
以下代码应该可以正常工作:
var soundURL: NSURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("movie_quote", ofType: "mp3")!)!
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
答案 2 :(得分:0)
您忘了在班上实施AVAudioPlayerDelegate
。我认为这应该是主要问题。
此外,您还应该在{。}}中添加prepareToPlay()
功能
@IBAction func playSlowAudio(sender: UIButton) {
audioPlayer.prepareToPlay()
audioPlayer.play()
}