Having AVAudioEngine repeat a sound
Asked Answered
B

1

10

I've been having trouble making the code below repeat the sound at audioURL over and over again. Right now it just plays it once when the view is opened, then stops.

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)
        myPlayer.play()


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Thanks!

Berwick answered 10/11, 2014 at 20:49 Comment(0)
B
19

After hours and hour of searching, this did it:

class aboutViewController: UIViewController {
       
    var audioEngine: AVAudioEngine = AVAudioEngine()
    var audioFilePlayer: AVAudioPlayerNode = AVAudioPlayerNode()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        
        let filePath: String = NSBundle.mainBundle().pathForResource("chimes", ofType: "wav")!
        println("\(filePath)")
        let fileURL: NSURL = NSURL(fileURLWithPath: filePath)!
        let audioFile = AVAudioFile(forReading: fileURL, error: nil)
        let audioFormat = audioFile.processingFormat
        let audioFrameCount = UInt32(audioFile.length)
        let audioFileBuffer = AVAudioPCMBuffer(PCMFormat: audioFormat, frameCapacity: audioFrameCount)
        audioFile.readIntoBuffer(audioFileBuffer, error: nil)
        
        var mainMixer = audioEngine.mainMixerNode
        audioEngine.attachNode(audioFilePlayer)
        audioEngine.connect(audioFilePlayer, to:mainMixer, format: audioFileBuffer.format)
        audioEngine.startAndReturnError(nil)
        
        audioFilePlayer.play()
        audioFilePlayer.scheduleBuffer(audioFileBuffer, atTime: nil, options:.Loops, completionHandler: nil)
    }

    ...
}
Berwick answered 10/11, 2014 at 21:53 Comment(1)
Will there be no memory problems using AVAudioPCMBuffer directly?Stink

© 2022 - 2024 — McMap. All rights reserved.