ios – Best Implementation of .wav Audio Recording in Swift

[ad_1]

Thanks in advance for your help,

I have been able to record in .m4a format for a while. Unfortunately, this project I’m working on needs to be recorded in .wav. I have been searching for a way of recording in .wav but I’ve only been able to find resources on converting to .wav after recording in .m4a. Is there a way of recording specifically in .wav?

The code I’ve pasted is my recording service. In settings specifically, I pass an audio format type. I haven’t been able to have this type be of ‘.wav’.

import Foundation

import Combine

import AVFoundation

class AudioRecorder: NSObject, ObservableObject {

override init() {
    super.init()
    fetchRecordings()
}

let objectWillChange = PassthroughSubject<AudioRecorder, Never>()

var audioRecorder: AVAudioRecorder!
    
var recordings = [Recording]()

var recording = false {
    didSet {
        objectWillChange.send(self)
    }
}

func startRecording(taskNum: Int) {
    let recordingSession = AVAudioSession.sharedInstance()
    
    
    do {
        try recordingSession.setCategory(.playAndRecord, mode: .default)
        try recordingSession.setActive(true)
    } catch {
        print("Failed to set up recording session")
    }
    
    let documentPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    
    let audioFilename = documentPath.appendingPathComponent("\(Date().toString(dateFormat: "dd-MM-YY_'at'_HH:mm:ss"))-task_\(taskNum).m4a")
    
    let settings = [
        // Change to kAudioFileWAVEType from kAudioFormatMPEG4AAC for .wav files?
        AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
        AVSampleRateKey: 12000,
        AVNumberOfChannelsKey: 1,
        AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
    ]
    
    do {
        audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
        audioRecorder.record()
        
        recording = true
    } catch {
        print("Could not start recording")
    }
}

func stopRecording() {
    audioRecorder.stop()
    recording = false
    
    fetchRecordings()
}

func fetchRecordings() {
    recordings.removeAll()
            
    let fileManager = FileManager.default
    let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let directoryContents = try! fileManager.contentsOfDirectory(at: documentDirectory, includingPropertiesForKeys: nil)
    for audio in directoryContents {
        let recording = Recording(fileURL: audio, createdAt: getCreationDate(for: audio))
        recordings.append(recording)
    }
    
    recordings.sort(by: { $0.createdAt.compare($1.createdAt) == .orderedAscending})
    objectWillChange.send(self)
}

func getCreationDate(for file: URL) -> Date {
    if let attributes = try? FileManager.default.attributesOfItem(atPath: file.path) as [FileAttributeKey: Any],
        let creationDate = attributes[FileAttributeKey.creationDate] as? Date {
        return creationDate
    } else {
        return Date()
    }
}

func deleteRecording(urlsToDelete: [URL]) {
    for url in urlsToDelete {
        print(url)
        do {
           try FileManager.default.removeItem(at: url)
        } catch {
            print("File could not be deleted!")
        }
    }
    
    fetchRecordings()
    
}

}

[ad_2]

Source link

Leave a Reply

Your email address will not be published.