How to record voice in .m4a format
Asked Answered
M

2

5

Already I have created an iPhone application to record. It will record in .caf file.

But I want to record in .m4a format.

Please help me to do this.

Thanks.

Muoimuon answered 25/11, 2010 at 16:53 Comment(0)
L
13

Here is an alternative code sample that will encode the file as AAC inside an m4a:

NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
NSURL *tmpFileUrl = [NSURL fileURLWithPath:[docsDir stringByAppendingPathComponent:@"tmp.m4a"]];
NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                        [NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,
                        [NSNumber numberWithFloat:16000.0], AVSampleRateKey,
                        [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
                        nil];
NSError *error = nil;
AVAudioRecorder *recorder = [[AVAudioRecorder alloc] initWithURL:tmpFileUrl settings:recordSettings error:&error];
[recorder prepareToRecord];

AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryRecord error:nil];
[session setActive:YES error:nil];

[recorder record];

Then to end the recording I used:

[recorder stop];
AVAudioSession *session = [AVAudioSession sharedInstance];
int flags = AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation;
[session setActive:NO withFlags:flags error:nil];

Then the file at 'tmpFileUrl' can be used.

Lawry answered 2/10, 2012 at 22:4 Comment(3)
You may want to wait for audioRecorderDidFinishRecording:successfully: to know whether the file is valid.Muleteer
Great, this worked perfectly for recording directly to *m4a without having to convert later. You should use AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation instead of AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation, because it has been deprecated since 4.0 (still works, but just in case).Tuberculate
Does anyone have an example app I can run to see this code in action? I was going to plug it in the sample Recorder app in the iOS dev center docs, but it's a little complex for me. Thanks!Andyane
H
7

Here is the working SWIFT code to record m4a Audio files. Bear in mind that hitting the right format parameters that produce usable audio files in iOS is really painful to find. I found that this combination works, after much trial and error. I hope it saves you time, enjoy!

let recordSettings: [String : AnyObject] = [AVSampleRateKey : NSNumber(float: Float(16000)),
                                                AVFormatIDKey : NSNumber(int: Int32(kAudioFormatMPEG4AAC)), 
        AVNumberOfChannelsKey : NSNumber(int: 1),
        AVEncoderAudioQualityKey : NSNumber(int: Int32(AVAudioQuality.Low.rawValue))]

func initializeAudioSession(){


    let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
        try audioRecorder = AVAudioRecorder(URL: self.directoryURL()!,
                                            settings: recordSettings)
        audioRecorder.delegate = self
        audioRecorder.meteringEnabled = true
        audioRecorder.prepareToRecord()
    } catch let error as NSError{
        print("ERROR Initializing the AudioRecorder - "+error.description)
    }
}

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

func directoryURL() -> NSURL { //filename helper method
        let fileManager = NSFileManager.defaultManager()
        let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        filepath = urls[0]
        let documentDirectory = urls[0] as NSURL
        print("STORAGE DIR: "+documentDirectory.description)
        //print("---filepath: "+(filepath?.description)!)
        let soundURL = documentDirectory.URLByAppendingPathComponent("recordedAudio.m4a") //.m4a
        print("SAVING FILE: "+soundURL.description)
        return soundURL
    }
Hangeron answered 6/6, 2016 at 12:43 Comment(2)
what format do you save the recording as? .caf? .m4a? it's unclear from your snippet.Hangeron
@Hangeron The snippet saves in m4a format, which is set in 2 places: 1) in the 'recordSettings' kAudioFormatMPEG4AAC parameter and 2) as an explicit .m4a extension that comes out of self.directoryURL(). I have added the code of directoryURL() to the answer so you can see where it comes from. Important: For some reason, most combinations of AVSampleRateKey and AVFormatIDKey recordingSettings actually crash, so you will be limited to the ones that work (I found out by trial and error)Hangeron

© 2022 - 2024 — McMap. All rights reserved.