How can I generate an array of floats from an audio file in Swift

前端 未结 4 593
遇见更好的自我
遇见更好的自我 2020-12-31 10:35

I would like to load mp3 and wav audio files as arrays of floats or doubles, similar to the io.wavfile.read function in scipy. I can do this with microphone data or playing

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-31 10:56

    It's really tricky to find everything about UnsafeBufferPointer

    Here I am posting updated code for Swift 5.0

    if let url = Bundle.main.url(forResource: "silence", withExtension: "mp3") {
        let file = try! AVAudioFile(forReading: url)
        if let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: file.fileFormat.sampleRate, channels: 1, interleaved: false) {
            if let buf = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 1024) {
                try! file.read(into: buf)
    
                // this makes a copy, you might not want that
                let floatArray = UnsafeBufferPointer(start: buf.floatChannelData![0], count:Int(buf.frameLength))
                // convert to data
                var data = Data()
                for buf in floatArray {
                    data.append(withUnsafeBytes(of: buf) { Data($0) })
                }
                // use the data if required.
            }
        }
    }
    

    Hope it will help you :)

提交回复
热议问题