ios - Swift 在读取原始数据文件并通过 audioPlayerNode.scheduleBuffer(audioFileBuffer) 播放时,我的音频质量很差
问题描述
我正在从原始文件中读取音频数据,然后将其转换为音频缓冲区。当我通过 audioPlayerNode 播放声音时,它会播放但音质不好。
func playMario() {
//See if the file exists.
guard let fileUrl: URL = Bundle.main.url(forResource: "mario", withExtension: "raw") else {
print("return");
return
}
do {
// Get the raw data from the file.
let rawData: Data = try Data(contentsOf: fileUrl)
// Return the raw data as an array of bytes.
// let bytes: [UInt8] = [UInt8](rawData)
let newBytes = Array(rawData)
// Convert byte array to audio buffer
let buffer = bytesToAudioBuffer(newBytes)
//starting of the player
audioEngine.attach(audioPlayerNode)
audioEngine.connect(audioPlayerNode, to:audioEngine.mainMixerNode, format: buffer.format)
audioEngine.prepare()
try? audioEngine.start()
audioPlayerNode.play()
audioPlayerNode.scheduleBuffer(buffer)
} catch {
print("Couldn't read the file.");
}
}
func bytesToAudioBuffer(_ buf: [UInt8]) -> AVAudioPCMBuffer {
//original sample rate 44100.0 //pcmFormatFloat32
let fmt = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 7000, channels: 1, interleaved: true)
let frameLength = UInt32(buf.count) / (fmt?.streamDescription.pointee.mBytesPerFrame)!
let audioBuffer = AVAudioPCMBuffer(pcmFormat: fmt!, frameCapacity: frameLength)
audioBuffer!.frameLength = frameLength
let dstLeft = audioBuffer?.floatChannelData![0]
buf.withUnsafeBufferPointer {
let src = UnsafeRawPointer($0.baseAddress!).bindMemory(to: Float.self, capacity: Int(frameLength))
dstLeft!.initialize(from: src, count: Int(frameLength))
}
return audioBuffer!
}
解决方案
推荐阅读
- python - 为什么 'data=data.dropna()' 和 'data.dropna(inplace=True)' 会产生不同的结果?
- android - Unity 5.6 为 Play 商店构建 64 位的 apk
- firefox - 是否所有 Firefox 网络流量都经过父进程
- docker - 是否可以为所有用户下载 Docker?
- r - 任何人都可以协助转换代码元素以使其运行吗?
- c# - GetStringAsync 持续时间过长且永不返回
- docker - Docker 环境变量定义
- android - sdkmanager 安装 cmake 失败
- css - 在溢出隐藏祖父母之外显示定位的 div
- python - 没有连接到 BLE 设备?使用黯淡:“AttributeError:'NoneType'对象没有属性'ConnectionStatusChanged'”