How to Send and Receive Live audio from one iPhone mic to the another iPhone speaker?

840 views Asked by At

I have managed to send and receive NSData from one iPhone to Another using Bonjour. I have wrote callbacks for recording audio using Audio Queue and sent the NSData using the following callback on the sender side:

    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);
}

In the above code I have managed to send the inBuffer->mAudioData converted to NSData and send it on the other iPhone. I have also received the same data on the receiver iPhone.

But now I do not know how to read this NSData. How to convert this data into an audio format and listen this audio on the speaker. Do I need to use Audio Queues on the receiver side or do I use simple AVPlayer to listen to the sound. If anyone can help solve it would be a great help.

1

There are 1 answers

0
Tommie C. On

To use the NSData just use the NSData writeToFile:atomically: method. Pass in the NSTemporary() path and append a path component like "temp.mp4". At that point you have a filePath with valid data that you can use to load the audio asset. AVAudioPlayer can support loading from a URL.

OR with iOS 7.0+

You can initialize the AVAudioPlayer directly with the NSData object.

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

et. al...