我正在尝试使用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是因为我需要在以后添加一些效果。
有人能帮我解决这个问题吗?
谢谢!

最佳答案

我运行了你的代码,运行得很好,我要检查三件事:
确保找到了您的文件,因此更改您的代码以使用AVAudioPlayer,检查程序是否知道文件在哪里,以及它是否可以播放该文件
其次,检查语句的位置,下面是我的代码示例。

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()
    }

}
希望这对你有帮助,如果你有任何问题的话!

关于iphone - 无法使用AVAudioEngine播放声音,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26369024/

10-10 06:26