2013-07-30 2 views
0

У меня есть объектный файл c, который содержит некоторые функции с делегатами asyncsocket. Я хочу создать глобальный объект, а затем в функции startRecord, используя эту глобальную переменную, вызывающую функцию connect и используя тот же объект в функции обратного вызова, вызывающий функцию writeToServer, которую я хочу вызвать. Но когда я пытаюсь получить доступ к этой глобальной переменной она даетКак получить доступ к глобальной переменной в функции обратного вызова

ошибку как «объект не определен» код, связанный это следующим образом:

server *srv; 

// ____________________________________________________________________________________ 
// AudioQueue callback function, called when an input buffers has been filled. 
void AQRecorder::MyInputBufferHandler( void *        inUserData, 
             AudioQueueRef      inAQ, 
             AudioQueueBufferRef     inBuffer, 
             const AudioTimeStamp *    inStartTime, 
             UInt32        inNumPackets, 
             const AudioStreamPacketDescription* inPacketDesc) 
{ 
    AQRecorder *aqr = (AQRecorder *)inUserData; 

    try { 
     NSLog(@"Checking NumPacket if > 0 "); 
     if (inNumPackets > 0) { 


      XThrowIfError(AudioFileWritePackets(aqr->mRecordFile, FALSE, inBuffer->mAudioDataByteSize, 
              inPacketDesc, aqr->mRecordPacket, &inNumPackets, inBuffer->mAudioData), 
         "AudioFileWritePackets failed"); 

      aqr->mRecordPacket += inNumPackets; 
      NSLog(@"size = %u",(unsigned int)inBuffer->mAudioDataByteSize); 

      // const int PCM_SIZE = 44100; 
      int MP3_SIZE = inBuffer->mAudioDataByteSize * 4; 
      // short int pcm_buffer[PCM_SIZE*2]; 
      unsigned char mp3_buffer[MP3_SIZE]; 
      // unsigned char * outBuf = (unsigned char *)malloc(MP3_SIZE); 
//   short int leftpcm[inNumPackets]; 
//   short int rightpcm[inNumPackets]; 
//    
//    
//    leftpcm[inNumPackets] = ((short int *)inBuffer->mAudioData)[2*inNumPackets]; 
//    rightpcm[inNumPackets] = ((short int *)inBuffer->mAudioData)[2 *inNumPackets + 1 ]; 

//   AudioQueueBufferRef *mp3buffer; 

      //memset(mp3_buffer, 0, sizeof(MP3_SIZE)); 
      lame_t lame = lame_init(); 
      lame_set_in_samplerate(lame, 44100); 
      lame_set_VBR(lame, vbr_default); 
      lame_init_params(lame); 
     // NSLog(@"data = %i",(unsigned int)inBuffer->mAudioDataByteSize); 


       int encodedBytes=lame_encode_buffer_interleaved(lame, (short int *)inBuffer->mAudioData , inNumPackets, mp3_buffer, MP3_SIZE); 
      [data appendBytes:mp3_buffer length:encodedBytes]; 

     if (inBuffer->mAudioDataByteSize != 0) {} 
      else{ 

       NSLog(@"Flush encoded buffer"); 
      int encode=lame_encode_flush(lame, mp3_buffer, MP3_SIZE); 
       [data appendBytes:mp3_buffer length:encode];} 



      srv = [[server alloc]init]; 
      srv.dataBuffer=data; 
      [srv serverWrite]; 
      mp3_buffer[MP3_SIZE]=nil; 

      [data release]; 


      lame_close(lame); 


     } 

     // if we're not stopping, re-enqueue the buffe so that it gets filled again 
     if (aqr->IsRunning()) 
      XThrowIfError(AudioQueueEnqueueBuffer(inAQ, inBuffer, 0, NULL), "AudioQueueEnqueueBuffer failed"); 
    } catch (CAXException e) { 
     char buf[256]; 
     fprintf(stderr, "Error: %s (%s)\n", e.mOperation, e.FormatError(buf)); 
    } 

} 

void AQRecorder::StartRecord(CFStringRef inRecordFile) 
{ 
    srv=[[server alloc]init]; 
    [srv connecting]; 

    int i, bufferByteSize; 
    UInt32 size; 
    CFURLRef url = nil; 

    try {  
     mFileName = CFStringCreateCopy(kCFAllocatorDefault, inRecordFile); 

//  // specify the recording format 
//  SetupAudioFormat(kAudioFormatMPEG4AAC); 

     // specify the recording format, use hardware AAC if available 
     // otherwise use IMA4 
//  if(IsAACHardwareEncoderAvailable()) 
//   SetupAudioFormat(kAudioFormatMPEG4AAC); 
//  else 
      SetupAudioFormat(kAudioFormatLinearPCM); 

     // create the queue 
     XThrowIfError(AudioQueueNewInput(
             &mRecordFormat, 
             MyInputBufferHandler, 
             this /* userData */, 
             NULL /* run loop */, NULL /* run loop mode */, 
             0 /* flags */, &mQueue), "AudioQueueNewInput failed"); 

     // get the record format back from the queue's audio converter -- 
     // the file may require a more specific stream description than was necessary to create the encoder. 
     mRecordPacket = 0; 

     size = sizeof(mRecordFormat); 
     XThrowIfError(AudioQueueGetProperty(mQueue, kAudioQueueProperty_StreamDescription, 
             &mRecordFormat, &size), "couldn't get queue's format"); 

     NSString *recordFile = [NSTemporaryDirectory() stringByAppendingPathComponent: (NSString*)inRecordFile]; 


     //url = CFURLCreateWithString(kCFAllocatorDefault, (CFStringRef)recordFile, NULL); 
     url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)recordFile, kCFURLPOSIXPathStyle, false); 
     // create the audio file 
     OSStatus status = AudioFileCreateWithURL(url, kAudioFileCAFType, &mRecordFormat, kAudioFileFlags_EraseFile, &mRecordFile); 
     CFRelease(url); 

     XThrowIfError(status, "AudioFileCreateWithURL failed"); 

     // copy the cookie first to give the file object as much info as we can about the data going in 
     // not necessary for pcm, but required for some compressed audio 
     CopyEncoderCookieToFile(); 

     // allocate and enqueue buffers 
     bufferByteSize = ComputeRecordBufferSize(&mRecordFormat, kBufferDurationSeconds); // enough bytes for half a second 
     for (i = 0; i < kNumberRecordBuffers; ++i) { 
      XThrowIfError(AudioQueueAllocateBuffer(mQueue, bufferByteSize, &mBuffers[i]), 
         "AudioQueueAllocateBuffer failed"); 

      XThrowIfError(AudioQueueEnqueueBuffer(mQueue, mBuffers[i], 0, NULL), 
         "AudioQueueEnqueueBuffer failed"); 
     } 
     // start the queue 
     mIsRunning = true; 
     XThrowIfError(AudioQueueStart(mQueue, NULL), "AudioQueueStart failed"); 
    } 
    catch (CAXException e) { 
     char buf[256]; 
     fprintf(stderr, "Error: %s (%s)\n", e.mOperation, e.FormatError(buf)); 
    } 
    catch (...) { 
     fprintf(stderr, "An unknown error occurred\n");; 
    } 

} 
+0

вы можете объявить, что varible глобально в AppDelegate и Acess это .. – Jitendra

ответ

0

ИЗУЧЕНИЯ ДАННОЙ LINK. И ТАМ EXPLAIN ЯСНО О глобальных переменных в CALLBACK ФУНКЦИИ http://dragonfiresdk.net/forum/index.php?topic=200.0

+0

CONCEPT объяснить тем, что я пробовал, но в случае функции обратного вызова не работает в моем случае дает ошибку «необъявленная переменная» – Naresh

+0

создание локальной переменной ее работы, но я хочу глобальную область. – Naresh

+0

Обратите внимание, что ссылки только для ответов не рекомендуется (ссылки, как правило, прерываются со временем). Пожалуйста, рассмотрите возможность редактирования своего ответа и добавления краткого описания здесь. (в качестве прохода вы не должны кричать) – bummi