Joe
Joe

Reputation: 353

Cannot play sound with AVAudioEngine

I am trying to play an audio file using the AVAudioEngine. I have seen several examples, and I'm just following the same steps. However, the sound is not being played. Here's my code:

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

The reason I am not simply using AVAudioPlayer is because I need to add later some effects.

Can anyone please help me out with that? Thanks!

Upvotes: 1

Views: 2918

Answers (1)

CarveDrone
CarveDrone

Reputation: 915

I ran your code, and it worked fine, there are three things I would check:

  1. Make sure your file is found, so change your code to work with AVAudioPlayer just to check that the program knows where the file is, and that it can play it
  2. Second, check where you are putting your statements, my example with the code is below.

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

    }

Hope this helps, ask if you have any questions!

Upvotes: 2

Related Questions