Play and record streaming audio
<p>I'm working on an iPhone app that should be able to play and record audio streaming data simultaneously. Is it actually possible? I'm trying to mix SpeakHere and AudioRecorder samples and getting an empty file with no audio data...</p>

<p>Here is my .m code:</p>

<pre><code>#import "AzRadioViewController.h"

@implementation azRadioViewController

static const CFOptionFlags kNetworkEvents = kCFStreamEventOpenCompleted |
kCFStreamEventHasBytesAvailable |
kCFStreamEventEndEncountered |
kCFStreamEventErrorOccurred;

void MyAudioQueueOutputCallback( void* inClientData, 
AudioQueueRef inAQ, 
AudioQueueBufferRef inBuffer,
const AudioTimeStamp *inStartTime, 
UInt32 inNumberPacketDescriptions, 
const AudioStreamPacketDescription* inPacketDesc
)
{
NSLog(@"start MyAudioQueueOutputCallback");


MyData* myData = (MyData*)inClientData;


NSLog(@"--- %i", inNumberPacketDescriptions);

if(inNumberPacketDescriptions == 0 &amp;&amp; myData-&gt;dataFormat.mBytesPerPacket != 0)
{
inNumberPacketDescriptions = inBuffer-&gt;mAudioDataByteSize / myData-&gt;dataFormat.mBytesPerPacket;
}


OSStatus status = AudioFileWritePackets(myData-&gt;audioFile, FALSE, inBuffer-&gt;mAudioDataByteSize,
inPacketDesc, myData-&gt;currentPacket, &amp;inNumberPacketDescriptions, inBuffer-&gt;mAudioData);


if(status == 0)
{
myData-&gt;currentPacket += inNumberPacketDescriptions;
}

NSLog(@"status:%i curpac:%i pcdesct: %i", status, myData-&gt;currentPacket, inNumberPacketDescriptions);


unsigned int bufIndex = MyFindQueueBuffer(myData, inBuffer);

pthread_mutex_lock(&amp;myData-&gt;mutex);
myData-&gt;inuse[bufIndex] = false;
pthread_cond_signal(&amp;myData-&gt;cond);
pthread_mutex_unlock(&amp;myData-&gt;mutex);
}


OSStatus StartQueueIfNeeded(MyData* myData)
{

NSLog(@"start StartQueueIfNeeded");

OSStatus err = noErr;
if (!myData-&gt;started) { 
err = AudioQueueStart(myData-&gt;queue, NULL);
if (err) { PRINTERROR("AudioQueueStart"); myData-&gt;failed = true; return err; } 
myData-&gt;started = true;
printf("started\n");
}
return err;
}



OSStatus MyEnqueueBuffer(MyData* myData)
{
NSLog(@"start MyEnqueueBuffer");


OSStatus err = noErr;
myData-&gt;inuse[myData-&gt;fillBufferIndex] = true; 

AudioQueueBufferRef fillBuf = myData-&gt;audioQueueBuffer[myData-&gt;fillBufferIndex];
fillBuf-&gt;mAudioDataByteSize = myData-&gt;bytesFilled; 
err = AudioQueueEnqueueBuffer(myData-&gt;queue, fillBuf, myData-&gt;packetsFilled, myData-&gt;packetDescs);
if (err) { PRINTERROR("AudioQueueEnqueueBuffer"); myData-&gt;failed = true; return err; } 



StartQueueIfNeeded(myData);

return err;
}


void WaitForFreeBuffer(MyData* myData)
{
NSLog(@"start WaitForFreeBuffer");

if (++myData-&gt;fillBufferIndex &gt;= kNumAQBufs) myData-&gt;fillBufferIndex = 0;
myData-&gt;bytesFilled = 0; 
myData-&gt;packetsFilled = 0; 

printf("-&gt;lock\n");
pthread_mutex_lock(&amp;myData-&gt;mutex); 
while (myData-&gt;inuse[myData-&gt;fillBufferIndex]) {
printf("... WAITING ...\n");
pthread_cond_wait(&amp;myData-&gt;cond, &amp;myData-&gt;mutex);
}
pthread_mutex_unlock(&amp;myData-&gt;mutex);
printf("&lt;-unlock\n");
}


int MyFindQueueBuffer(MyData* myData, AudioQueueBufferRef inBuffer)
{
NSLog(@"start MyFindQueueBuffer");

for (unsigned int i = 0; i &lt; kNumAQBufs; ++i) {
if (inBuffer == myData-&gt;audioQueueBuffer[i]) 
return i;
}
return -1;
}


void MyAudioQueueIsRunningCallback( void* inClientData, 
AudioQueueRef inAQ, 
AudioQueuePropertyID inID)
{
NSLog(@"start MyAudioQueueIsRunningCallback");

MyData* myData = (MyData*)inClientData;

UInt32 running;
UInt32 size;
OSStatus err = AudioQueueGetProperty(inAQ, kAudioQueueProperty_IsRunning, &amp;running, &amp;size);
if (err) { PRINTERROR("get kAudioQueueProperty_IsRunning"); return; }
if (!running) {
pthread_mutex_lock(&amp;myData-&gt;mutex);
pthread_cond_signal(&amp;myData-&gt;done);
pthread_mutex_unlock(&amp;myData-&gt;mutex);
}
}


void MyPropertyListenerProc( void * inClientData,
AudioFileStreamID inAudioFileStream,
AudioFileStreamPropertyID inPropertyID,
UInt32 * ioFlags)
{ 
NSLog(@"start MyPropertyListenerProc");

MyData* myData = (MyData*)inClientData;
OSStatus err = noErr;

printf("found property '%c%c%c%c'\n", (inPropertyID&gt;&gt;24)&amp;255, (inPropertyID&gt;&gt;16)&amp;255, (inPropertyID&gt;&gt;8)&amp;255, inPropertyID&amp;255);


switch (inPropertyID) {
case kAudioFileStreamProperty_ReadyToProducePackets :
{

AudioStreamBasicDescription asbd;
UInt32 asbdSize = sizeof(asbd);



err = AudioFileStreamGetProperty(inAudioFileStream, kAudioFileStreamProperty_DataFormat, &amp;asbdSize, &amp;asbd);
if (err) { PRINTERROR("get kAudioFileStreamProperty_DataFormat"); myData-&gt;failed = true; break; }

err = AudioQueueNewOutput(&amp;asbd, MyAudioQueueOutputCallback, myData, NULL, NULL, 0, &amp;myData-&gt;queue);
if (err) { PRINTERROR("AudioQueueNewOutput"); myData-&gt;failed = true; break; }


for (unsigned int i = 0; i &lt; kNumAQBufs; ++i) {
err = AudioQueueAllocateBuffer(myData-&gt;queue, kAQBufSize, &amp;myData-&gt;audioQueueBuffer[i]);
if (err) { PRINTERROR("AudioQueueAllocateBuffer"); myData-&gt;failed = true; break; }
}

UInt32 cookieSize;
Boolean writable;
err = AudioFileStreamGetPropertyInfo(inAudioFileStream, kAudioFileStreamProperty_MagicCookieData, &amp;cookieSize, &amp;writable);
if (err) { PRINTERROR("info kAudioFileStreamProperty_MagicCookieData"); break; }
printf("cookieSize %d\n", cookieSize);

void* cookieData = calloc(1, cookieSize);
err = AudioFileStreamGetProperty(inAudioFileStream, kAudioFileStreamProperty_MagicCookieData, &amp;cookieSize, cookieData);
if (err) { PRINTERROR("get kAudioFileStreamProperty_MagicCookieData"); free(cookieData); break; }

err = AudioQueueSetProperty(myData-&gt;queue, kAudioQueueProperty_MagicCookie, cookieData, cookieSize);
free(cookieData);
if (err) { PRINTERROR("set kAudioQueueProperty_MagicCookie"); break; }

err = AudioQueueAddPropertyListener(myData-&gt;queue, kAudioQueueProperty_IsRunning, MyAudioQueueIsRunningCallback, myData);
if (err) { PRINTERROR("AudioQueueAddPropertyListener"); myData-&gt;failed = true; break; }





break;
}
}
}


static void
ReadStreamClientCallBack(CFReadStreamRef stream, CFStreamEventType type, void *clientCallBackInfo) {

NSLog(@"start ReadStreamClientCallBack");

if(type == kCFStreamEventHasBytesAvailable) {

UInt8 buffer[2048];
CFIndex bytesRead = CFReadStreamRead(stream, buffer, sizeof(buffer));


if (bytesRead &lt; 0) {
}

else if (bytesRead) {
OSStatus err = AudioFileStreamParseBytes(globalMyData-&gt;audioFileStream, bytesRead, buffer, 0);
if (err) { PRINTERROR("AudioFileStreamParseBytes"); }
}
}
}


void MyPacketsProc(void * inClientData,
UInt32 inNumberBytes,
UInt32 inNumberPackets,
const void * inInputData,
AudioStreamPacketDescription *inPacketDescriptions)
{
NSLog(@"start MyPacketsProc");
MyData* myData = (MyData*)inClientData;

printf("got data. bytes: %d packets: %d\n", inNumberBytes, inNumberPackets);

for (int i = 0; i &lt; inNumberPackets; ++i) {
SInt64 packetOffset = inPacketDescriptions[i].mStartOffset;
SInt64 packetSize = inPacketDescriptions[i].mDataByteSize;

size_t bufSpaceRemaining = kAQBufSize - myData-&gt;bytesFilled;
if (bufSpaceRemaining &lt; packetSize) {
MyEnqueueBuffer(myData);
WaitForFreeBuffer(myData);
}

AudioQueueBufferRef fillBuf = myData-&gt;audioQueueBuffer[myData-&gt;fillBufferIndex];
memcpy((char*)fillBuf-&gt;mAudioData + myData-&gt;bytesFilled, (const char*)inInputData + packetOffset, packetSize);
myData-&gt;packetDescs[myData-&gt;packetsFilled] = inPacketDescriptions[i];
myData-&gt;packetDescs[myData-&gt;packetsFilled].mStartOffset = myData-&gt;bytesFilled;
myData-&gt;bytesFilled += packetSize;
myData-&gt;packetsFilled += 1;


size_t packetsDescsRemaining = kAQMaxPacketDescs - myData-&gt;packetsFilled;
if (packetsDescsRemaining == 0) {
MyEnqueueBuffer(myData);
WaitForFreeBuffer(myData);
}
} 




}

- (IBAction)buttonPlayPressedid)sender
{

label.text = @"Buffering";
[self connectionStart];
}




- (IBAction)buttonSavePressedid)sender
{
NSLog(@"save");

AudioFileClose(myData.audioFile);
AudioQueueDispose(myData.queue, TRUE);

}

bool getFilename(char* buffer,int maxBufferLength)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
NSUserDomainMask, YES); 
NSString* docDir = [paths objectAtIndex:0];
NSString* file = [docDir stringByAppendingString:@"/rec.caf"];
return [file getCString:buffer maxLength:maxBufferLength encoding:NSUTF8StringEncoding];
}

-(void)connectionStart {


@try {

MyData* myData = (MyData*)calloc(1, sizeof(MyData));

globalMyData = myData;

pthread_mutex_init(&amp;myData-&gt;mutex, NULL);
pthread_cond_init(&amp;myData-&gt;cond, NULL);
pthread_cond_init(&amp;myData-&gt;done, NULL);

NSLog(@"Start");


myData-&gt;dataFormat.mSampleRate = 16000.0f;
myData-&gt;dataFormat.mFormatID = kAudioFormatLinearPCM;
myData-&gt;dataFormat.mFramesPerPacket = 1;
myData-&gt;dataFormat.mChannelsPerFrame = 1;
myData-&gt;dataFormat.mBytesPerFrame = 2;
myData-&gt;dataFormat.mBytesPerPacket = 2;
myData-&gt;dataFormat.mBitsPerChannel = 16;
myData-&gt;dataFormat.mReserved = 0;
myData-&gt;dataFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;


int i, bufferByteSize;
UInt32 size;



AudioQueueNewInput(
&amp;myData-&gt;dataFormat,
MyAudioQueueOutputCallback,
&amp;myData,
NULL /* run loop */, kCFRunLoopCommonModes /* run loop mode */,
0 /* flags */, &amp;myData-&gt;queue);



size = sizeof(&amp;myData-&gt;dataFormat);
AudioQueueGetProperty(&amp;myData-&gt;queue, kAudioQueueProperty_StreamDescription, 
&amp;myData-&gt;dataFormat, &amp;size);




CFURLRef fileURL;
char path[256];
memset(path,0,sizeof(path));
getFilename(path,256);

fileURL = CFURLCreateFromFileSystemRepresentation(NULL, (UInt8*)path, strlen(path), FALSE);

AudioFileCreateWithURL(fileURL,
kAudioFileCAFType,
&amp;myData-&gt;dataFormat,
kAudioFileFlags_EraseFile,
&amp;myData-&gt;audioFile);

OSStatus err = AudioFileStreamOpen(myData, MyPropertyListenerProc, MyPacketsProc, 
kAudioFileMP3Type, &amp;myData-&gt;audioFileStream);
if (err) { PRINTERROR("AudioFileStreamOpen"); return 1; }

CFStreamClientContext ctxt = {0, self, NULL, NULL, NULL};

CFStringRef bodyData = CFSTR(""); // Usually used for POST data
CFStringRef headerFieldName = CFSTR("X-My-Favorite-Field");
CFStringRef headerFieldValue = CFSTR("Dreams");

CFStringRef url = CFSTR(RADIO_LOCATION);
CFURLRef myURL = CFURLCreateWithString(kCFAllocatorDefault, url, NULL);
CFStringRef requestMethod = CFSTR("GET");
CFHTTPMessageRef myRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, requestMethod, myURL, kCFHTTPVersion1_1);

CFHTTPMessageSetBody(myRequest, bodyData);
CFHTTPMessageSetHeaderFieldValue(myRequest, headerFieldName, headerFieldValue);


CFReadStreamRef stream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, myRequest);

if (!stream) {
NSLog(@"Creating the stream failed");
return;
}



if (!CFReadStreamSetClient(stream, kNetworkEvents, ReadStreamClientCallBack, &amp;ctxt)) {
CFRelease(stream);
NSLog(@"Setting the stream's client failed.");
return;
}

CFReadStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);

if (!CFReadStreamOpen(stream)) {
CFReadStreamSetClient(stream, 0, NULL, NULL);
CFReadStreamUnscheduleFromRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
CFRelease(stream);
NSLog(@"Opening the stream failed.");
return;
}

}
@catch (NSException *exception) {
NSLog(@"main: Caught %@: %@", [exception name], [exception reason]); 
}
}


- (void)viewDidLoad {
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
[super viewDidLoad];
}


- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
}


- (void)dealloc {
[super dealloc];
}

@end
</code></pre>
