gpt4 book ai didi

ios - 尝试使用 AVAudioPlayer 快速播放音频时出错

转载 作者:可可西里 更新时间:2023-11-01 02:19:34 25 4
gpt4 key购买 nike

我对编码还很陌生,我曾尝试实现此处类似问题的其他答案中建议的代码,但没有成功。该应用程序构建良好,但每次我去播放实际的音频文件时,我都会收到一条错误消息,提示“ fatal error :在展开可选值 (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()
}

最佳答案

这是播放音频和停止音频的完整工作代码:

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示例项目以获取更多信息。

关于ios - 尝试使用 AVAudioPlayer 快速播放音频时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31792422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com