gpt4 book ai didi

ios - 如何播放从 NSData 转换而来的 AVAudioPCMBuffer 中的音频

转载 作者:搜寻专家 更新时间:2023-10-31 23:02:55 25 4
gpt4 key购买 nike

我从像这样的 udp 数据包中获取音频 PCM 16 位单声道数据:

(void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
...
}

我正在通过如下调用 swift 函数将此数据转换为 PCM 缓冲区:

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:1024*10)
PCMBuffer.frameLength = PCMBuffer.frameCapacity

let channels = UnsafeBufferPointer(start: PCMBuffer.floatChannelData, count: Int(PCMBuffer.format.channelCount))

data.getBytes(UnsafeMutablePointer<Void>(channels[0]) , length: data.length)

return PCMBuffer
}

数据被转换为 PCM 缓冲区,我可以在日志中看到它的长度。但是当我尝试播放缓冲区时,我听不到任何声音。这是接收代码:

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:1024*10)
PCMBuffer.frameLength = PCMBuffer.frameCapacity

let channels = UnsafeBufferPointer(start: PCMBuffer.floatChannelData, count: Int(PCMBuffer.format.channelCount))

data.getBytes(UnsafeMutablePointer<Void>(channels[0]) , length: data.length)
var mainMixer = audioEngine.mainMixerNode
audioEngine.attachNode(audioFilePlayer)
audioEngine.connect(audioFilePlayer, to:mainMixer, format: PCMBuffer.format)
audioEngine.startAndReturnError(nil)

audioFilePlayer.play()
audioFilePlayer.scheduleBuffer(PCMBuffer, atTime: nil, options: nil, completionHandler: nil)
return PCMBuffer
}

最佳答案

最终使用了 objective-c 函数:数据转换正常

-(AudioBufferList *) getBufferListFromData: (NSData *) data
{
if (data.length > 0)
{
NSUInteger len = [data length];
//NSData *d2 = [data subdataWithRange:NSMakeRange(4, 1028)];
//I guess you can use Byte*, void* or Float32*. I am not sure if that makes any difference.
Byte* byteData = (Byte*) malloc (len);
memcpy (byteData, [data bytes], len);
if (byteData)
{
AudioBufferList * theDataBuffer =(AudioBufferList*)malloc(sizeof(AudioBufferList) * 1);
theDataBuffer->mNumberBuffers = 1;
theDataBuffer->mBuffers[0].mDataByteSize =(UInt32) len;
theDataBuffer->mBuffers[0].mNumberChannels = 1;
theDataBuffer->mBuffers[0].mData = byteData;
// Read the data into an AudioBufferList
return theDataBuffer;
}
}
return nil;
}

关于ios - 如何播放从 NSData 转换而来的 AVAudioPCMBuffer 中的音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31423790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com