这是一个迟到的答案,但我很难获得一个float *
缓冲区来写入 Swift 中的文件。
发布此示例以防万一它对某人有所帮助。
enum AudioFileError: ErrorType {
case FailedToCreate(OSStatus)
case FailedToWrite(OSStatus)
case FailedToClose(OSStatus)
}
func writeAudioData(audioData:NSData, toFile destination:NSURL, description:AudioStreamBasicDescription) throws {
//get a pointer to the float buffer
let floatBuffer = UnsafeMutablePointer<Float>(audioData.bytes)
//get an AudioBufferList from the float buffer
let buffer = AudioBuffer(mNumberChannels: 1, mDataByteSize: UInt32(audioData.length), mData: floatBuffer)
var bufferList = AudioBufferList(mNumberBuffers: 1, mBuffers: buffer)
//create the CAF file using the stream description
var file = ExtAudioFileRef()
var result:OSStatus = noErr
var streamDescription = description
withUnsafePointer(&streamDescription) { streamDescription in
withUnsafeMutablePointer(&file) { file in
result = ExtAudioFileCreateWithURL(destination, kAudioFileCAFType, streamDescription, nil, AudioFileFlags.EraseFile.rawValue, file)
}
}
if result != noErr {
throw AudioFileError.FailedToCreate(result)
}
//write the AudioBufferList to the file
withUnsafeMutablePointer(&bufferList) { bufferList in
result = ExtAudioFileWrite(file, UInt32(audioData.length / sizeof(Float)), bufferList)
}
if result != noErr {
throw AudioFileError.FailedToWrite(result)
}
//close the file
result = ExtAudioFileDispose(file)
if result != noErr {
throw AudioFileError.FailedToClose(result)
}
}