我正在尝试使用AVAudioEngine播放音频文件。我看过几个例子,我只是按照相同的步骤。但是,声音没有播放。这是我的代码:
var audioUrl = NSURL(fileURLWithPath: "my-path-to-audio-file")
var audioEngine = AVAudioEngine()
var myPlayer = AVAudioPlayerNode()
audioEngine.attachNode(myPlayer)
var audioFile = AVAudioFile(forReading: audioUrl, error: nil)
var audioError: NSError?
audioEngine.connect(myPlayer, to: audioEngine.mainMixerNode, format: audioFile.processingFormat)
myPlayer.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
audioEngine.startAndReturnError(&audioError)
myPlayer.play()
我不仅仅是使用AVAudioPlayer的原因是因为我需要稍后添加一些效果。
任何人都可以帮我解决这个问题吗? 谢谢!
答案 0 :(得分:2)
我运行了你的代码,它工作正常,我会检查三件事:
其次,检查你的陈述在哪里,我的代码示例如下。
import UIKit
import AVFoundation
class aboutViewController: UIViewController {
var audioUrl = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("chimes", ofType: "wav")!)
var audioEngine = AVAudioEngine()
var myPlayer = AVAudioPlayerNode()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
audioEngine.attachNode(myPlayer)
var audioFile = AVAudioFile(forReading: audioUrl, error: nil)
var audioError: NSError?
audioEngine.connect(myPlayer, to: audioEngine.mainMixerNode, format: audioFile.processingFormat)
myPlayer.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
audioEngine.startAndReturnError(&audioError)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func testSound(sender: AnyObject) {
myPlayer.play()
}
}
希望这有帮助,请问您是否有任何问题!