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
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 :)