Skip raw NSData format
Why not use AVAudioPlayer fully? If you really need NSData , you can always download such data from soundURL below. In this example, the disk buffer looks something like this:
let soundURL = documentDirectory.URLByAppendingPathComponent("sound.m4a")
It makes sense to write directly to the file anyway for optimal memory and resource management. You get NSData from your record as follows:
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 {} }
Customization
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 the Xcode project:
Here you can find this example here . Download the complete project, which records and plays both on the simulator and on the device, from Swift Recipes .
source share