gpt4 book ai didi

ios - 如何从 Swift 中的音频文件生成一个 float 数组

转载 作者:搜寻专家 更新时间:2023-10-30 21:52:02 25 4
gpt4 key购买 nike

我想将 mp3 和 wav 音频文件加载为 float 或 double 组,类似于 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))
}

最佳答案

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

遗憾的是,对于 double 来说,将 .PCMFormatFloat32 替换为 .PCMFormatFloat64 似乎还不够,因为 AVAudioPCMBuffer 没有float64ChannelData 方法。

更新,因为我不太了解 swift

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

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

关于ios - 如何从 Swift 中的音频文件生成一个 float 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34751294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com