How to write array of float values to audio file in Core Audio?

a 夏天 提交于 2019-12-02 04:00:22

The free DiracLE time stretching library ( http://dirac.dspdimension.com ) has utility code that converts ABLs (AudioBufferLists) into float arrays and vice-versa as part of their example code. Check out their EAFRead and EAFWrite classes, they're exactly what you're looking for.

Yes, I'd put them in an AudioBuffer and that into an AudioBufferList. After that you can write them to a file using ExtAudioFileWrite() on a ExtAudioFileRef that was created using ExtAudioFileCreateNew().

Audio File documentation: http://developer.apple.com/library/mac/#documentation/MusicAudio/Reference/ExtendedAudioFileServicesReference/Reference/reference.html%23//apple_ref/doc/uid/TP40007912

This is a late answer, but I struggled to get a float * buffer to write to a file in Swift.

Posting this example in case it helps someone.

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)
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!