Swift中如何创建processingFormat为Int16的音频文件?
解决AVAudioFile创建Int16格式音频文件的问题
你遇到的问题是因为processingFormat是AVAudioFile内部处理音频时使用的格式,苹果默认用Float32做内部运算,这和你最终写入文件的实际格式无关。真正决定文件存储格式的是你传入的settings参数,你可以通过打印audioFile?.fileFormat来确认实际的文件格式。
如果要确保最终生成的WAV文件是Int16格式,你可以按以下方式调整代码:
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let audioURL = documentDirectory.appendingPathComponent("recording_\(UUID().uuidString).wav") // 明确定义Int16格式的设置 let audioSettings: [String: Any] = [ AVFormatIDKey: kAudioFormatLinearPCM, AVSampleRateKey: 16000, AVNumberOfChannelsKey: 1, AVLinearPCMBitDepthKey: 16, AVLinearPCMIsFloatKey: false, AVLinearPCMIsBigEndianKey: false, AVLinearPCMIsNonInterleavedKey: false ] do { audioFile = try AVAudioFile(forWriting: audioURL, settings: audioSettings) // 打印实际文件格式和内部处理格式 if let fileFormat = audioFile?.fileFormat { print("File format: \(fileFormat)") } if let processingFormat = audioFile?.processingFormat { print("Processing format: \(processingFormat)") } // 示例:写入Int16格式的音频数据 let sampleCount = 16000 // 1秒的测试数据 var int16Data = [Int16](repeating: 0, count: sampleCount) for i in 0..<sampleCount { let value = sin(2 * .pi * 440 * Double(i)/16000) * Int16.max int16Data[i] = Int16(value) } // 将Int16数据转换为AVAudioBuffer let buffer = AVAudioPCMBuffer(pcmFormat: AVAudioFormat(settings: audioSettings)!, frameCapacity: AVAudioFrameCount(sampleCount))! buffer.frameLength = AVAudioFrameCount(sampleCount) let int16Pointer = buffer.int16ChannelData![0] for i in 0..<sampleCount { int16Pointer[i] = int16Data[i] } // 写入文件 try audioFile?.write(from: buffer) } catch { print("Error creating audio file: \(error.localizedDescription)") }
关键说明
processingFormat始终显示Float32是正常现象,它只是苹果内部处理音频的标准格式,不影响最终文件的存储格式。- 通过
audioSettings明确指定AVLinearPCMIsFloatKey: false和AVLinearPCMBitDepthKey: 16,确保文件以Int16格式存储。 - 写入数据时,要将Int16数据填充到
AVAudioPCMBuffer的int16ChannelData缓冲区中,而非使用Float32类型的缓冲区。
内容的提问来源于stack exchange,提问作者trip xp
相关产品推荐
相关产品推荐

