Search code examples
iosswiftaudiosignal-processingaudiotoolbox

Get stream of raw samples from audio signal using AudioToolbox - Swift


I would like to record an audio signal with my iPhone and then I would like to access the samples of this signal one-by-one. I found some similar examples online but I never found an example (in Swift) to actually read and manipulate all the raw samples. How can I do that using Swift?


Solution

  • I solved my problem, I was finally able to create an array of floats where to store and manipulate the audio samples, doing the following:

       let file: AVAudioFile!
        do {
            file = try AVAudioFile(forReading: mySourceURL!)
        } catch {
            print("Error:", error)
            return
        }
        let totSamples = file.length
        let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: file.fileFormat.sampleRate, channels: 1, interleaved: false)
        let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(totSamples))
        try! file.read(into: buffer)
        var floatArray = Array(UnsafeBufferPointer(start: buffer.floatChannelData?[0], count:Int(buffer.frameLength)))
    

    where mySourceURL! is the URL of the recorded signal.