如何从Swift中的audio文件生成一个浮点数组

我想加载的MP3和WAVaudio文件作为数组浮动或双打,类似于在scipy io.wavfile.read函数。 我可以用麦克风数据来做到这一点,或通过将audiostream写入缓冲区来播放audio。 但是,我不知道如何一次加载所有的audio文件的数据。

– 更新

对于将来使用audio信号数据的任何人来说,这里有一个function可以实现。 这是基于Rhythmic Fistman的回答。

func loadAudioSignal(audioURL: NSURL) -> (signal: [Float], rate: Double, frameCount: Int) { let file = try! AVAudioFile(forReading: audioURL) let format = AVAudioFormat(commonFormat: .PCMFormatFloat32, sampleRate: file.fileFormat.sampleRate, channels: file.fileFormat.channelCount, interleaved: false) let buf = AVAudioPCMBuffer(PCMFormat: format, frameCapacity: UInt32(file.length)) try! file.readIntoBuffer(buf) // You probably want better error handling let floatArray = Array(UnsafeBufferPointer(start: buf.floatChannelData[0], count:Int(buf.frameLength))) return (signal: floatArray, rate: file.fileFormat.sampleRate, frameCount: Int(file.length)) } 

AVAudioFile内置到iOS(和OS X),非常方便,也将为你做格式转换:

 import AVFoundation // ... let url = NSBundle.mainBundle().URLForResource("your audio file", withExtension: "wav") let file = try! AVAudioFile(forReading: url!) let format = AVAudioFormat(commonFormat: .PCMFormatFloat32, sampleRate: file.fileFormat.sampleRate, channels: 1, interleaved: false) let buf = AVAudioPCMBuffer(PCMFormat: format, frameCapacity: 1024) try! file.readIntoBuffer(buf) // this makes a copy, you might not want that let floatArray = Array(UnsafeBufferPointer(start: buf.floatChannelData[0], count:Int(buf.frameLength))) print("floatArray \(floatArray)\n") 

不幸的是,对于双打,它似乎不足以用.PCMFormatFloat64replace.PCMFormatFloat32 ,因为AVAudioPCMBuffer没有float64ChannelData方法。

更新,因为我不知道迅速

您可以通过使用UnsafeBufferPointer来避免复制数组,这是一个非常好的集合types:

 let floatArray = UnsafeBufferPointer(start: buf.floatChannelData[0], count:Int(buf.frameLength))