Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to record audio in wav format in Swift?

I have searched everywhere for this and i couldn't find proper way of doing it. I have succeeded in recording in .wav format, but the problem is, when i try reading raw data from recorded .wav file, some chunks are in wrong place/aren't there at all.

My code for recording audio:

    func startRecording(){

    let audioSession = AVAudioSession.sharedInstance()

    try! audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
    try! audioSession.setActive(true)
    audioSession.requestRecordPermission({(allowed: Bool) -> Void in print("Accepted")} )


    let settings: [String : AnyObject] = [
        AVFormatIDKey:Int(kAudioFormatLinearPCM),
        AVSampleRateKey:44100.0,
        AVNumberOfChannelsKey:1,
        AVLinearPCMBitDepthKey:8,
        AVLinearPCMIsFloatKey:false,
        AVLinearPCMIsBigEndianKey:false,
        AVEncoderAudioQualityKey:AVAudioQuality.Max.rawValue
    ]

    let date = NSDate()

    let df = NSDateFormatter()
    df.dateFormat = "yyyy-MM-dd-HH:mm:ss"

    let dfString = df.stringFromDate(date)

    let fullPath = documentsPath.stringByAppendingString("/\(dfString).wav")

    recorder = try! AVAudioRecorder(URL: NSURL(string: fullPath)!, settings: settings)
    recorder.delegate = self
    recorder.prepareToRecord()
    recorder.record()

}

When i print out data of recorder audio file, i get weird number where 'd' 'a' 't' 'a' should be written, following by zeros. And then, in middle of of data, it appears.

No 64617461 ('d' 'a' 't' 'a') chunk - it should be in place of 464c4c52

64617461 ('d' 'a' 't' 'a') at random spot after a lot of zeros no 64617461 ('d' 'a' 't' 'a') enter image description here

Is there better way of recording wav file? I am not sure why is this happening, so any help would be appreciated. Should i maybe record in other format then convert it to raw?

Thanks and sorry for so many images.

like image 659
Uros19 Avatar asked Oct 31 '22 13:10

Uros19


1 Answers

I think only the fmt chunk is guaranteed to come first. It looks like it's fine to have other chunks before the data chunk, so just skip over non-data chunks.

From http://soundfile.sapp.org/doc/WaveFormat/

A RIFF file starts out with a file header followed by a sequence of data chunks.

You need to update your parser :)

like image 130
Rhythmic Fistman Avatar answered Nov 04 '22 10:11

Rhythmic Fistman