热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

将AVAudioPCMBuffer转换为NSData并返回

如何解决《将AVAudioPCMBuffer转换为NSData并返回》经验,为你挑选了2个好方法。

如何转换AVAudioPCMBufferNSData?如果应该这样做

let data = NSData(bytes: buffer.floatChannelData, length: bufferLength)

那怎么算bufferLength

以及如何转换NSDataAVAudioPCMBuffer



1> Rod Chen..:

缓冲区长度为frameCapacity*bytesPerFrame.以下是可以在NSData和AVAudioPCMBuffer之间进行转换的函数.

func toNSData(PCMBuffer: AVAudioPCMBuffer) -> NSData {
    let channelCount = 1  // given PCMBuffer channel count is 1
    var channels = UnsafeBufferPointer(start: PCMBuffer.floatChannelData, count: channelCount)
    var ch0Data = NSData(bytes: channels[0], length:Int(PCMBuffer.frameCapacity * PCMBuffer.format.streamDescription.memory.mBytesPerFrame))
    return ch0Data
}       

func toPCMBuffer(data: NSData) -> AVAudioPCMBuffer {
    let audioFormat = AVAudioFormat(commonFormat: AVAudioCommonFormat.PCMFormatFloat32, sampleRate: 8000, channels: 1, interleaved: false)  // given NSData audio format
    var PCMBuffer = AVAudioPCMBuffer(PCMFormat: audioFormat, frameCapacity: UInt32(data.length) / audioFormat.streamDescription.memory.mBytesPerFrame)
    PCMBuffer.frameLength = PCMBuffer.frameCapacity
    let channels = UnsafeBufferPointer(start: PCMBuffer.floatChannelData, count: Int(PCMBuffer.format.channelCount))
    data.getBytes(UnsafeMutablePointer(channels[0]) , length: data.length)
    return PCMBuffer
}


我成功地在`AVAudioPCMBuffer`中转换`NSData`(我不需要反向,所以没有那个代码):http://pastebin.com/raw/m5c74FPA

2> Brian King..:

如果通过audioBufferList API复制,则复制缓冲区要容易得多。不管实际缓冲区的格式是什么,这都适用。

extension Data {
    init(buffer: AVAudioPCMBuffer, time: AVAudioTime) {
        let audioBuffer = buffer.audioBufferList.pointee.mBuffers
        self.init(bytes: audioBuffer.mData!, count: Int(audioBuffer.mDataByteSize))
    }

    func makePCMBuffer(format: AVAudioFormat) -> AVAudioPCMBuffer? {
        let streamDesc = format.streamDescription.pointee
        let frameCapacity = UInt32(count) / streamDesc.mBytesPerFrame
        guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCapacity) else { return nil }

        buffer.frameLength = buffer.frameCapacity
        let audioBuffer = buffer.audioBufferList.pointee.mBuffers

        withUnsafeBytes { addr in
            audioBuffer.mData?.copyMemory(from: addr, byteCount: Int(audioBuffer.mDataByteSize))
        }

        return buffer
    }
}


推荐阅读
author-avatar
突击手丶罪域
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有