无法用AVAudioEngine播放声音

时间:2014-10-14 19:42:18

标签: iphone swift

我正在尝试使用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的原因是因为我需要稍后添加一些效果。

任何人都可以帮我解决这个问题吗? 谢谢!

1 个答案:

答案 0 :(得分:2)

我运行了你的代码,它工作正常,我会检查三件事:

  1. 确保找到您的文件,因此更改您的代码以使用AVAudioPlayer只是为了检查程序是否知道该文件的位置以及它可以播放它
  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()
        }
    

    }

  3. 希望这有帮助,请问您是否有任何问题!