How to record audio in wav format in Swift?

I searched everywhere for this, and I could not find the right way to do this. I managed to write in .wav format, but the problem is that when I try to read the source data from the recorded .wav file, some fragments are in the wrong place / none 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 the data of the audio file of the recorder, I get a strange number where 'd' 'a' 't' 'a' should be written, following the zeros. And then, in the middle of the data, appears.

No 64617461 ('d' 'a' 't' 'a') piece - it should be instead of 464c4c52

64617461 ('d' 'a' 't' 'a') in a random place after many zeros no 64617461 ('d' 'a' 't' 'a') enter image description here

wav ? , , . , raw?

.

+4
1

, fmt . , data, data.

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

RIFF , .

:)

+2

Source: https://habr.com/ru/post/1619977/


All Articles