我想将mp3和wav音频文件作为浮点数或双精度数组加载,类似于scipy中的io.wavfile.read函数.我可以通过将音频流写入缓冲区来使用麦克风数据或播放音频.但是,我不确定如何一次加载所有音频文件的数据.
- 更新
对于将来使用音频信号数据的任何人来说,这是一个可以解决问题的功能.它基于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))
}
Run Code Online (Sandbox Code Playgroud)
Rhy*_*man 13
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")
Run Code Online (Sandbox Code Playgroud)
可悲的是,对于双打来说,似乎没有足够的替代.PCMFormatFloat32,.PCMFormatFloat64因为AVAudioPCMBuffer没有float64ChannelData方法.
更新因为我不太清楚
您可以通过使用UnsafeBufferPointer,这是一个非常好的集合类型避免复制数组:
let floatArray = UnsafeBufferPointer(start: buf.floatChannelData[0], count:Int(buf.frameLength))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3021 次 |
| 最近记录: |