Play audio from AVAudioPCMBuffer with AVAudioEngine Play audio from AVAudioPCMBuffer with AVAudioEngine swift swift

Play audio from AVAudioPCMBuffer with AVAudioEngine


Skip the raw NSData format

Why not use AVAudioPlayer all the way? If you positively need NSData, you can always load such data from the soundURL below. In this example, the disk buffer is something like:

let soundURL = documentDirectory.URLByAppendingPathComponent("sound.m4a")

It makes sense to record directly to a file anyway for optimal memory and resource management. You get NSData from your recording this way:

let data = NSFileManager.defaultManager().contentsAtPath(soundURL.path())

The code below is all you need:

Record

if !audioRecorder.recording {    let audioSession = AVAudioSession.sharedInstance()    do {        try audioSession.setActive(true)        audioRecorder.record()    } catch {}}

Play

if (!audioRecorder.recording){    do {        try audioPlayer = AVAudioPlayer(contentsOfURL: audioRecorder.url)        audioPlayer.play()    } catch {}}

Setup

let audioSession = AVAudioSession.sharedInstance()do {    try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)    try audioRecorder = AVAudioRecorder(URL: self.directoryURL()!,        settings: recordSettings)    audioRecorder.prepareToRecord()} catch {}

Settings

let recordSettings = [AVSampleRateKey : NSNumber(float: Float(44100.0)),    AVFormatIDKey : NSNumber(int: Int32(kAudioFormatMPEG4AAC)),    AVNumberOfChannelsKey : NSNumber(int: 1),    AVEncoderAudioQualityKey : NSNumber(int: Int32(AVAudioQuality.Medium.rawValue))]

Download Xcode Project:

You can find this very example here. Download the full project, which records and plays on both simulator and device, from Swift Recipes.