iphone - 如何从一个 iPhone 麦克风向另一个 iPhone 扬声器发送和接收实时音频?

标签 iphone ios objective-c core-audio audioqueue

我已经成功地使用 Bonjour 从一部 iPhone 向另一部 iPhone 发送和接收 NSData。我已经使用音频队列编写了用于录制音频的回调,并在发送端使用以下回调发送了 NSData:

    void AudioInputCallback(void * inUserData,
                    AudioQueueRef inAQ,
                    AudioQueueBufferRef inBuffer,
                    const AudioTimeStamp * inStartTime,
                    UInt32 inNumberPacketDescriptions,
                    const AudioStreamPacketDescription * inPacketDescs)
{
RecordState * recordState = (RecordState*)inUserData;
if (!recordState->recording)
{
    printf("Not recording, returning\n");
}

// if (inNumberPacketDescriptions == 0 && recordState->dataFormat.mBytesPerPacket != 0)
// {
//     inNumberPacketDescriptions = inBuffer->mAudioDataByteSize / recordState->dataFormat.mBytesPerPacket;
// }

printf("Writing buffer %lld\n", recordState->currentPacket);

OSStatus status = AudioFileWritePackets(recordState->audioFile,
                                        false,
                                        inBuffer->mAudioDataByteSize,
                                        inPacketDescs,
                                        recordState->currentPacket,
                                        &inNumberPacketDescriptions,
                                        inBuffer->mAudioData);
NSLog(@"DATA = %@",[NSData dataWithBytes:inBuffer->mAudioData length:inBuffer->mAudioDataByteSize]);

[[NSNotificationCenter defaultCenter] postNotificationName:@"Recording" object:[NSData dataWithBytes:inBuffer->mAudioData length:inBuffer->mAudioDataByteSize]];

if (status == 0)
{
    recordState->currentPacket += inNumberPacketDescriptions;
}

AudioQueueEnqueueBuffer(recordState->queue, inBuffer, 0, NULL);
}

在上面的代码中,我设法将 inBuffer->mAudioData 转换为 NSData 并发送到另一部 iPhone。我在接收器 iPhone 上也收到了相同的数据。

但现在我不知道如何读取这个 NSData。如何将此数据转换为音频格式并在扬声器上收听此音频。我需要在接收方使用音频队列还是使用简单的 AVPlayer 来收听声音。如果有人可以帮助解决它,那将是一个很大的帮助。

最佳答案

要使用 NSData 只需使用 NSData writeToFile:atomically: 方法。传入 NSTemporary() 路径并附加一个路径组件,如“temp.mp4”。那时你有一个包含有效数据的文件路径,你可以使用它来加载音频 Assets 。 AVAudioPlayer 可以支持从 URL 加载。

或使用 iOS 7.0+

您可以直接使用 NSData 对象初始化 AVAudioPlayer。

init(data data: NSData, fileTypeHint utiString: String?) throws

等。 ……

关于iphone - 如何从一个 iPhone 麦克风向另一个 iPhone 扬声器发送和接收实时音频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18692880/

相关文章:

ios - "id"类型如何在不强制转换的情况下理解方法的接收者?

iphone - 在 EKReminder 中设置 startDateComponents 时出现 "Invalid date component"错误

iphone - 在基于 Window 的应用程序中连接 socket ,Objective-C

c# - MonoTouch 中的事件变为空

iphone - -JSONValue 失败。错误是 : Unexpected end of input

objective-c - 加快保存图像 - iOS

iphone - 如何开始 iPhone 编程?

ios - 消息通知如何从通知托盘中消失?

objective-c - 如何避免/避免导致过度保留NSClipViewBackingLayer的垃圾收集错误

objective-c - NSArrayController 更改不会传播到绑定(bind)的 NSUserDefaults