title: Send audio over socket in C
body: <p>I am trying to send audio to a server that I built through a socket. I am using C for the client. Basically my code records a max of 10 seconds of audio and then I want to send it to my server through a socket. How can I send the audio that was recorded through a socket in C? I don't want to save the audio as a file... I want to send it directly to the server.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>// Standard libraries
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;netinet/in.h&gt;
  
  // Audio libraries
  #include "portaudio.h"
  
  // Audio parameters
  #define RECORD_AUDIO_THRESHOLD 0.003
  #define SILENCE_SECONDS 1
  #define MAX_RECORDING_SECONDS 10
  #define AUDIO_FORMAT paFloat32
  typedef float SAMPLE_TYPE;
  #define NUM_INPUT_CHANNELS 1
  #define NUM_OUTPUT_CHANNELS 1
  #define SAMPLE_RATE 44100
  #define FRAMES_PER_BUFFER 512
  
  // Server details
  #define SERVER_ADDRESS "127.0.0.1"
  #define SERVER_PORT 8080
  
  // Global variables
  int sock = 0;
  
  // ######################## Structures ########################
  
  typedef struct
  {
      int             recording;
      int             maxFrameIndex;
      int             currentFrameIndex;
      int             silenceStartFrameIndex;
      double          averageAmplitude;
      SAMPLE_TYPE     *recordedSamples;
  }
  paAudioData;
  
  // ######################## Helper Functions ########################
  
  void setup(void)
  {
  
  }
  
  // ######################## Helper Functions ########################
  
  
  
  // ######################## Callbacks ########################
  
  static int paListeningCallback( const void *inputBuffer,
                                  void *outputBuffer,
                                  unsigned long framesPerBuffer,
                                  const PaStreamCallbackTimeInfo* timeInfo,
                                  PaStreamCallbackFlags statusFlags,
                                  void *userData  )
  {
      paAudioData *data = (paAudioData*)userData;
      const SAMPLE_TYPE *rptr = (const SAMPLE_TYPE*)inputBuffer;
      SAMPLE_TYPE *wptr = &amp;data-&gt;recordedSamples[data-&gt;currentFrameIndex * NUM_INPUT_CHANNELS];
      unsigned long framesLeft = data-&gt;maxFrameIndex - data-&gt;currentFrameIndex;
      SAMPLE_TYPE amplitude, frameData;
      long framesToCalc, i;
      int j;
  
      // Prevent unused variable warnings.
      (void) outputBuffer;
      (void) timeInfo;
      (void) statusFlags;
      (void) userData;
  
      if (framesLeft &lt; framesPerBuffer &amp;&amp; data-&gt;recording)
          framesToCalc = framesLeft;
      else
          framesToCalc = framesPerBuffer;
  
      for (i = 0; i &lt; framesToCalc; i++)
      {
          frameData = *rptr++;
          amplitude = frameData;
          if (amplitude &lt; 0) amplitude = -amplitude; // ABS
          if ((amplitude - data-&gt;averageAmplitude) &gt;= RECORD_AUDIO_THRESHOLD)
          {
              if (!(data-&gt;recording))
              {
                  data-&gt;recording = 1;
                  data-&gt;currentFrameIndex = 0;
                  printf("Recording...\n");
              }
              data-&gt;silenceStartFrameIndex = 0;
              for (j = 0; j &lt; NUM_INPUT_CHANNELS; j++) *wptr++ = frameData;
          }
          else if (data-&gt;recording)
          {
              if (data-&gt;silenceStartFrameIndex == 0) data-&gt;silenceStartFrameIndex = data-&gt;currentFrameIndex + i;
  
              if ((data-&gt;currentFrameIndex + i) == data-&gt;silenceStartFrameIndex + (SILENCE_SECONDS * SAMPLE_RATE * NUM_INPUT_CHANNELS))
              {
                  data-&gt;recording = 0;
                  data-&gt;currentFrameIndex += i;
                  printf("Stopped recording.\n");
  
                  // TODO: Send audio to server via socket
  
                  return 0;
              }
              for (j = 0; j &lt; NUM_INPUT_CHANNELS; j++) *wptr++ = frameData;
          }
      }
      data-&gt;currentFrameIndex += framesToCalc;
      return 0;
  }
  
  // ######################## Main ########################
  
  int main(void)
  {
      PaStream*           stream;
      PaError             err;
      paAudioData         data;
      int                 i,
                          totalFrames,
                          numSamples,
                          numBytes;
      struct sockaddr_in  address;
      int                 valread;
      struct sockaddr_in  serv_addr;
      char                buffer[2048] = {0};
  
      setup();
  
      if ((sock = socket(AF_INET, SOCK_STREAM, 0)) &lt; 0)
      {
          printf("\n Socket creation error \n");
          return -1;
      }
  
      memset(&amp;serv_addr, '0', sizeof(serv_addr));
  
      serv_addr.sin_family = AF_INET;
      serv_addr.sin_port = htons(SERVER_PORT);
  
      // Convert IPv4 and IPv6 addresses from text to binary form
      if(inet_pton(AF_INET, SERVER_ADDRESS, &amp;serv_addr.sin_addr) &lt;= 0)
      {
          printf("\nInvalid address/ Address not supported \n");
          return -1;
      }
  
      if (connect(sock, (struct sockaddr *)&amp;serv_addr, sizeof(serv_addr)) &lt; 0)
      {
          printf("\nConnection Failed \n");
          return -1;
      }
  
      // Initialize audio data
      data.maxFrameIndex = totalFrames = MAX_RECORDING_SECONDS * SAMPLE_RATE;
      data.currentFrameIndex = 0;
      numSamples = totalFrames * NUM_INPUT_CHANNELS;
      numBytes = numSamples * sizeof(SAMPLE_TYPE);
      data.recordedSamples = (SAMPLE_TYPE *) malloc(numBytes);
      data.averageAmplitude = 0;
      data.recording = 0;
  
      // Initialize PortAudio
      err = Pa_Initialize();
      if (err != paNoError) goto paError;
  
      // Open an audio listening stream
      err = Pa_OpenDefaultStream( &amp;stream,
                                  NUM_INPUT_CHANNELS,
                                  0,
                                  AUDIO_FORMAT,
                                  SAMPLE_RATE,
                                  FRAMES_PER_BUFFER,
                                  paListeningCallback,
                                  &amp;data  );
      if (err != paNoError) goto paError;
  
      // Start passive audio listening
      err = Pa_StartStream(stream);
      if (err != paNoError) goto paError;
  
      Pa_Sleep(10000);
  
      // Terminate PortAudio
      err = Pa_Terminate();
      if (err != paNoError) goto paError;
  
      // Print PortAudio error and exit
      paError:
          printf("PortAudio error: %s\n", Pa_GetErrorText(err));
          return 0;
  
      return 0;
  }
  </code></pre>