Exemple #1
0
int main(void)
{
    int      i;
    PaError  err;
    PABLIO_Stream     *aInStream;
    PABLIO_Stream     *aOutStream;
    int      index;

    printf("Full duplex sound test using PABLIO\n");
    fflush(stdout);

    /* Open simplified blocking I/O layer on top of PortAudio. */
    /* Open input first so it can start to fill buffers. */
    err = OpenAudioStream( &aInStream, SAMPLE_RATE, SAMPLE_TYPE,
                           (PABLIO_READ | PABLIO_STEREO) );
    if( err != paNoError ) goto error;
    /* printf("opened input\n");  fflush(stdout); /**/

    err = OpenAudioStream( &aOutStream, SAMPLE_RATE, SAMPLE_TYPE,
                           (PABLIO_WRITE | PABLIO_STEREO) );
    if( err != paNoError ) goto error;
    /* printf("opened output\n");  fflush(stdout); /**/

    /* Process samples in the foreground. */
    index = 0;
    for( i=0; i<(NUM_SECONDS * SAMPLE_RATE); i++ )
    {
        /* Write old frame of data to output. */
        /* samples[index][1] = (i&256) * (1.0f/256.0f); /* sawtooth */
        WriteAudioStream( aOutStream, &samples[index][0], 1 );

        /* Read one frame of data into sample array for later output. */
        ReadAudioStream( aInStream, &samples[index][0], 1 );
        index += 1;
        if( index >= NUM_ECHO_FRAMES ) index = 0;

        if( (i & 0xFFFF) == 0 ) printf("i = %d\n", i );
        fflush(stdout); /**/
    }

    CloseAudioStream( aOutStream );
    CloseAudioStream( aInStream );

    printf("R/W echo sound test complete.\n" );
    fflush(stdout);
    return 0;

error:
    fprintf( stderr, "An error occured while using PortAudio\n" );
    fprintf( stderr, "Error number: %d\n", err );
    fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) );
    return -1;
}
Exemple #2
0
int main(void)
{
    PABLIO_Stream *inStream, *outStream;

    OpenAudioStream(&inStream,  44100, paInt16, PABLIO_MONO|PABLIO_READ);
    OpenAudioStream(&outStream, 44100, paInt16, PABLIO_MONO|PABLIO_WRITE);

    while(1) { // pass audio in to audio out one buffer at a time forever
        // using blocking read and write calls which provide flow control
        ReadAudioStream(  inStream, buffer, NUM_FRAMES);

        // process samples in buffer here as desired

        WriteAudioStream(outStream, buffer, NUM_FRAMES);
    }
}
Exemple #3
0
int main(int argc, char *argv[])
{
   PABLIO_Stream  *outStream;

   double theta  = 0.0;
   double theta1 = 0.0;
   double  delta, delta1;
   double frequency1 = FREQUENCY1;
   double attenuation = 0.1;


   if (argc > 1)
      frequency1 = atof(argv[1]);
   if (argc > 2)
      attenuation = atof(argv[2]);

   delta  = FREQUENCY  * 2.0 * 3.1415 / (double) SAMPLE_RATE;
   delta1 = frequency1 * 2.0 * 3.1415 / (double) SAMPLE_RATE;

   OpenAudioStream(&outStream, SAMPLE_RATE, paFloat32, PABLIO_WRITE|PABLIO_MONO);

   int x;
   while(1) {  // synthesize and output samples forever
      for(x= 0; x<NUM_FRAMES; x++) { // synthesize a buffer full of samples
	 buffer[x] = sin(theta) * 0.9 + sin(theta1) * attenuation;
         theta+= delta;
         theta1+= delta1;
      }

      // blocking write provides flow control
      WriteAudioStream(outStream, buffer, NUM_FRAMES); 
   }

   CloseAudioStream(outStream);
}
Exemple #4
0
int main(void)
{
   float buffer[NUM_FRAMES];
   PABLIO_Stream *inStream, *outStream;
   int x;
   double time = 0.0;
   double lastTime = 0.0;
   double delta = 1.0/SAMPLE_RATE;

   OpenAudioStream(&inStream, SAMPLE_RATE, paFloat32, PABLIO_READ|PABLIO_MONO);

   while (1)
   {
      ReadAudioStream(inStream, buffer, NUM_FRAMES);
      for (x = 0; x < NUM_FRAMES; x++) 
      {
         if ((buffer[x] > 0.20) && (buffer[x] > buffer[x-1]) && (time - lastTime > DEBOUNCE_THRESHOLD))
         {
            printf("%f (%f)\n", time, time-lastTime);
            lastTime = time;
         }
         time += delta;
      }
   }
}
Exemple #5
0
int main(void)
{
    int             i,j;
    PaError         err;
    PABLIO_Stream  *aOutStream;

    printf("Generate sawtooth waves using PABLIO.\n");
    fflush(stdout);

    /* Open simplified blocking I/O layer on top of PortAudio. */
    err = OpenAudioStream( &aOutStream, SAMPLE_RATE, paFloat32,
                           (PABLIO_WRITE | PABLIO_STEREO) );
    if( err != paNoError ) goto error;

    /* Initialize oscillator phases. */
    phases[0] = 0.0;
    phases[1] = 0.0;

    for( i=0; i<(NUM_SECONDS * SAMPLE_RATE); i += FRAMES_PER_BLOCK )
    {
        /* Generate sawtooth waveforms in a block for efficiency. */
        for( j=0; j<FRAMES_PER_BLOCK; j++ )
        {
            /* Generate a sawtooth wave by incrementing a variable. */
            phases[0] += PHASE_INCREMENT;
            /* The signal range is -1.0 to +1.0 so wrap around if we go over. */
            if( phases[0] > 1.0f ) phases[0] -= 2.0f;
            samples[j][0] = phases[0];

            /* On the second channel, generate a sawtooth wave a fifth higher. */
            phases[1] += PHASE_INCREMENT * (3.0f / 2.0f);
            if( phases[1] > 1.0f ) phases[1] -= 2.0f;
            samples[j][1] = phases[1];
        }

        /* Write samples to output. */
        WriteAudioStream( aOutStream, samples, FRAMES_PER_BLOCK );
    }

    CloseAudioStream( aOutStream );

    printf("Sawtooth sound test complete.\n" );
    fflush(stdout);
    return 0;

error:
    fprintf( stderr, "An error occured while using PABLIO\n" );
    fprintf( stderr, "Error number: %d\n", err );
    fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) );
    return -1;
}
Exemple #6
0
int main(void)
{
    int             i,j;
    PaError         err;
    PABLIO_Stream  *aOutStream;

    printf("Generate unsigned 8 bit sawtooth waves using PABLIO.\n");
    fflush(stdout);

    /* Open simplified blocking I/O layer on top of PortAudio. */
    err = OpenAudioStream( &aOutStream, SAMPLE_RATE, paUInt8,
                           (PABLIO_WRITE | PABLIO_STEREO) );
    if( err != paNoError ) goto error;

    /* Initialize oscillator phases to "ground" level for paUInt8. */
    phases[0] = 128;
    phases[1] = 128;

    for( i=0; i<(NUM_SECONDS * SAMPLE_RATE); i += FRAMES_PER_BLOCK )
    {
        /* Generate sawtooth waveforms in a block for efficiency. */
        for( j=0; j<FRAMES_PER_BLOCK; j++ )
        {
            /* Generate a sawtooth wave by incrementing a variable. */
            phases[0] += 1;
            /* We don't have to do anything special to wrap when using paUint8 because
             * 8 bit arithmetic automatically wraps. */
            samples[j][0] = phases[0];

            /* On the second channel, generate a higher sawtooth wave. */
            phases[1] += 3;
            samples[j][1] = phases[1];
        }

        /* Write samples to output. */
        WriteAudioStream( aOutStream, samples, FRAMES_PER_BLOCK );
    }

    CloseAudioStream( aOutStream );

    printf("Sawtooth sound test complete.\n" );
    fflush(stdout);
    return 0;

error:
    fprintf( stderr, "An error occured while using PABLIO\n" );
    fprintf( stderr, "Error number: %d\n", err );
    fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) );
    return -1;
}
Exemple #7
0
int main(void)
{
   PABLIO_Stream  *outStream;

   OpenAudioStream(&outStream, SAMPLE_RATE, paFloat32, PABLIO_WRITE|PABLIO_MONO);

   while(1) {  // synthesize and output samples forever
      before = GetAudioStreamWriteable(outStream);
      WriteAudioStream(outStream, &buffer, NUM_FRAMES); 
      after = GetAudioStreamWriteable(outStream);
      printf("%ld, %ld\n", before, after);

      sleep(2);
   }
}
Exemple #8
0
int main(void) {
   
   int i, j, k, dlength, bufferIndex=0;
   float scale[8] =                            //  E scale frequencies
      {164.81,184.99,207.65,220.00,
       246.94,277.18,311.12,329.62};
   short wg_l[DMAX], wg_r[DMAX];               // Waveguide delay lines
   short output;
   long temp;
   PABLIO_Stream *outStream;
   short buffer[NUM_FRAMES];

   OpenAudioStream(&outStream, SAMPLE_RATE, paInt16, PABLIO_WRITE|PABLIO_MONO);

   for (j=0;j<8;j++)   {                       // Play up the scale
      dlength = SAMPLE_RATE / scale[j] / 2;         // Setup waveguide length
      for (k=0;k<=dlength/2;k++) {            // Setup pluck
	 temp = 20000 * (long) k * 2;
	 temp /= dlength;
	 wg_l[k] = temp;
	 wg_l[dlength-k] = temp;
	 wg_r[k] = temp;
	 wg_r[dlength-k] = temp;
      }
      for (i=0;i<SAMPLE_RATE;i++)   {        // Play each note for 1 second
	 temp = wg_l[0];                     // stash delay outputs
	 output = wg_r[0];
	 for (k=0;k<dlength-1;k++) {         // Do delay lines
	    wg_l[k] = wg_l[k+1];
	    wg_r[k] = wg_r[k+1];
	 }
	 wg_l[dlength-1] = output*-0.99;     // Do reflections
	 wg_r[dlength-1] = -temp;
	 buffer[bufferIndex++] = output;
	 if (bufferIndex >= NUM_FRAMES){
	    WriteAudioStream(outStream, buffer, NUM_FRAMES);
	    bufferIndex = 0;
	 }
      }
   }

   if (bufferIndex > 0)
      WriteAudioStream(outStream, buffer, bufferIndex+1);
   CloseAudioStream(outStream);
}
Exemple #9
0
int main(void)
{
   PABLIO_Stream  *outStream;
   double theta = 0.0, delta = FREQUENCY * 2.0 * 3.1415 / (double)SAMPLE_RATE;
   int x; 

   OpenAudioStream(&outStream, SAMPLE_RATE, paFloat32, PABLIO_WRITE|PABLIO_MONO);

   while(1) {  // synthesize and output samples forever
      for(x= 0; x<NUM_FRAMES; x++) { // synthesize a buffer full of samples
           buffer[x] = sin(theta); // ugly, I know...
           theta+= delta;
      }

      // blocking write provides flow control
      WriteAudioStream(outStream, buffer, NUM_FRAMES); 
   }
}
Exemple #10
0
bool SoundDevice::pablio_input(bool state) {
  if(state && !aInStream) {
    err = OpenAudioStream( &aInStream, SAMPLE_RATE, PA_SAMPLE_TYPE,
			   (PABLIO_READ | PABLIO_STEREO) );
    if( err != paNoError) {
      Pa_Terminate();
      error("error opening input sound device: %s",Pa_GetErrorText( err ) );
      return false;
    } else
      info_input = Pa_GetDeviceInfo( Pa_GetDefaultInputDeviceID() );

  } else if(!state && aInStream) {

    CloseAudioStream(aInStream);
    aInStream = NULL;
    info_input = NULL;

  }
  return true;
}
Exemple #11
0
void outputAudio( double sampleRate, double duration, Source& source, Sequencer& sequencer ){
    static const int length = 64;
    float output[length];

    double secondsPerVector = (double)length / sampleRate;
    sequencer.beginPlayback();

    PABLIO_Stream *stream;
    OpenAudioStream( &stream, sampleRate, paFloat32, PABLIO_WRITE | PABLIO_MONO );

    unsigned long count = (sampleRate / length) * duration;
    for( unsigned long i=0; i<count; ++i ){
        std::fill_n( output, length, 0.f );  // zero output
        source.synthesize( output, length );
        sequencer.update( secondsPerVector );
        WriteAudioStream( stream, output, length );
    }

    CloseAudioStream( stream );
}
Exemple #12
0
int main(void)
{
   PABLIO_Stream  *outStream;
   int bufferSamples;
   float *buffer = createChirp(SAMPLE_RATE, 440.0, PERIOD, &bufferSamples);

   printf("buffernumSamples = %d\n", bufferSamples);

   OpenAudioStream(&outStream, SAMPLE_RATE, paFloat32, PABLIO_WRITE|PABLIO_MONO);

   while (1) 
   {
      // synthesize and output samples forever
      // before = GetAudioStreamWriteable(outStream);
      WriteAudioStream(outStream, buffer, bufferSamples); 
      // after = GetAudioStreamWriteable(outStream);
      // printf("%ld, %ld\n", before, after);

      sleep(1);
   }

   free(buffer);
}
Exemple #13
0
int main(void)
{
    int      i;
    SAMPLE   samples[SAMPLES_PER_FRAME * FRAMES_PER_BLOCK];
    PaError  err;
    PABLIO_Stream     *aStream;

    printf("Full duplex sound test using PortAudio and RingBuffers\n");
    fflush(stdout);

    /* Open simplified blocking I/O layer on top of PortAudio. */
    err = OpenAudioStream( &aStream, SAMPLE_RATE, SAMPLE_TYPE,
                           (PABLIO_READ_WRITE | PABLIO_STEREO) );
    if( err != paNoError ) goto error;

    /* Process samples in the foreground. */
    for( i=0; i<(NUM_SECONDS * SAMPLE_RATE); i += FRAMES_PER_BLOCK )
    {
        /* Read one block of data into sample array from audio input. */
        ReadAudioStream( aStream, samples, FRAMES_PER_BLOCK );
        /* Write that same block of data to output. */
        WriteAudioStream( aStream, samples, FRAMES_PER_BLOCK );
    }

    CloseAudioStream( aStream );

    printf("Full duplex sound test complete.\n" );
    fflush(stdout);
    return 0;

error:
    Pa_Terminate();
    fprintf( stderr, "An error occured while using the portaudio stream\n" );
    fprintf( stderr, "Error number: %d\n", err );
    fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) );
    return -1;
}
Exemple #14
0
ad_rec_t *ad_open_sps (int32 samples_per_sec)
{
  PaError err;

  ad_rec_t *handle;

  if ((handle = (ad_rec_t *) calloc (1, sizeof(ad_rec_t))) == NULL) {
      fprintf(stderr, "calloc(%ld) failed\n", sizeof(ad_rec_t));
      abort();
  }

  handle->sps = samples_per_sec;
  handle->bps = AD_SAMPLE_SIZE;

  /* Open simplified blocking I/O layer on top of PortAudio. */
  err = OpenAudioStream( &(handle->stream), handle->sps, SAMPLE_TYPE,
			 (PABLIO_READ | PABLIO_MONO) );

  if( err != paNoError ) {
    free(handle);
    return NULL;
  }

  handle->recording = 0;

  /*
   * Initialize recording; else there'll be a bunch of 0 frames at the
   * begining that will throw off the spectral analysis
   * hmm... it looks like this can happen any time, not just at the beginning...
   ad_start_rec(handle);
   sleep(1);
   ad_stop_rec(handle);
   */

  return handle;
}
Exemple #15
0
static int open_audio(){
    /* this will open one circular audio stream */
    /* build on top of portaudio routines */
    /* implementation based on file pastreamio.c */

    int numSamples;
    int numBytes;

    int minNumBuffers;
    int numFrames;

    minNumBuffers = 2 * Pa_GetMinNumBuffers( FRAMES_PER_BUFFER, vi.rate );
    numFrames = minNumBuffers * FRAMES_PER_BUFFER;
    numFrames = RoundUpToNextPowerOf2( numFrames );

    numSamples = numFrames * vi.channels;
    numBytes = numSamples * sizeof(SAMPLE);

    samples = (SAMPLE *) malloc( numBytes );

    /* store our latency calculation here */
    latency_sec =  (double) numFrames / vi.rate / vi.channels;
    printf( "Latency: %.04f\n", latency_sec );

    err = OpenAudioStream( &aOutStream, vi.rate, PA_SAMPLE_TYPE,
                           (PASTREAMIO_WRITE | PASTREAMIO_STEREO) );
    if( err != paNoError ) goto error;
    return err;
error:
    CloseAudioStream( aOutStream );
    printf( "An error occured while opening the portaudio stream\n" );
    printf( "Error number: %d\n", err );
    printf( "Error message: %s\n", Pa_GetErrorText( err ) );
    return err;

}
Exemple #16
0
UINT CFlvUtils::InitStreams()
{
   HRESULT hr = S_OK;

   if (!m_szFlvFile)
      hr = E_FAIL;

   // Add the audio and video streams using the default format codecs
   // and initialize the codecs
   if (SUCCEEDED(hr))
   {
      if (m_pAVOutputFormat->video_codec != CODEC_ID_NONE)
      {
         //_tprintf(_T("### codec supports video.\n"));
         m_pAVStreamVideo = AddVideoStream(m_pAVOutputFormat->video_codec);
         if (m_pAVStreamVideo == NULL)
         {
            hr = E_FAIL;
            _ftprintf(stderr, _T("Error in CFlvUtils::Init():\n Could not allocate video stream!\n"));
            // TODO: error handling?
         }
      }
   }
   if (SUCCEEDED(hr))
   {
      if (m_pAVOutputFormat->audio_codec != CODEC_ID_NONE)
      {
         //_tprintf(_T("### codec supports audio.\n"));
         m_pAVStreamAudio = AddAudioStream(m_pAVOutputFormat->audio_codec);
         if (m_pAVStreamAudio == NULL)
         {
            hr = E_FAIL;
            _ftprintf(stderr, _T("Error in CFlvUtils::Init():\n Could not allocate audio stream!\n"));
            // TODO: error handling?
         }
      }
   }
   if (SUCCEEDED(hr))
   {
      // Set the output parameters (must be done even if no parameters).
      if (av_set_parameters(m_pAVFormatContext, NULL) < 0)
      {
         _ftprintf(stderr, _T("Error in CFlvUtils::Init():\n Invalid output format parameters!\n"));
         hr = E_FAIL;
         // TODO: error handling?
      }
   }

   if (SUCCEEDED(hr))
   {
      // Dump codec format info to the shell
      dump_format(m_pAVFormatContext, 0, m_szFlvFile, 1);
   }

   // Now that all the parameters are set, we can open the audio and 
   // video codecs and allocate the necessary encode buffers
   if (SUCCEEDED(hr))
   {
      if (m_pAVStreamVideo)
         hr = OpenVideoStream();
   }
   if (SUCCEEDED(hr))
   {
      if (m_pAVStreamAudio)
         hr = OpenAudioStream();
   }

   return hr;
}
Exemple #17
0
int main(int argc, char* argv[]) {
   unsigned char	TuneSelection;
   unsigned char	CurrentOctave;
   unsigned char	ScriptIndex;
   unsigned char	BassDrumIsOn;
   unsigned short       BassDrumPointerIncrement;
   unsigned char	BassDrumDurationCount;
   unsigned short       BassDrumOutput;

   unsigned char	CurrentNoteEvent;
   unsigned char	NoteDurationCount;
   unsigned char	NoteIndex;
   unsigned short       NotePointerIncrement;
   unsigned short       NoteWavePointer;
   unsigned short       NoteAndBDOutput;
   unsigned char	NoteSynthOutput;

   unsigned short       TempoCounter;
   unsigned short       OverFlow;
   unsigned char	*WaveRAM;
   unsigned char	WaveINDEX;
   unsigned char        temp1 = 255;
   signed char temp2;
   short buffer[NUM_FRAMES];
   PABLIO_Stream *outStream;

   if (argc != 2){
     //printf("RockGuitar: Needs number 0-5\n");
     exit;
   } 
   temp2 = temp1;
   //wave table data for note synthesizer has the routine variables as its origin
   WaveRAM = &TuneSelection;
   OpenAudioStream(&outStream, SAMPLE_RATE, paInt16, PABLIO_WRITE|PABLIO_MONO);
   printf("Starting Synthesis!\n");
   //client input, tune selector Jukebox
   TuneSelection = (unsigned char) atoi (argv[1]);
   printf("Selected Tune Script is %d\n",TuneSelection);

   //first time initialization
   CurrentOctave            = 3;	//octave state
   ScriptIndex              = 0;	//index to Tune script elements
   BassDrumIsOn             = 0xff;	//0xff = True, 0x00 = False
   BassDrumPointerIncrement = 0x07ff;	//pitch for first bass drum event
   BassDrumDurationCount    = 0x30;	//duration for Bass Drum event

   CurrentNoteEvent = TuneScripts[TuneSelection][ScriptIndex++];	//prime pump, Sequencer gets first script element
   while(CurrentNoteEvent != 0xff){ //0xff is the end of script element
      if( ((CurrentNoteEvent & 0xf0)) == 0xf0){
   	 // control element  only octave is currently defined
   	 if( (CurrentNoteEvent & 0x0f) < 8){ // if note event
   	    CurrentOctave = CurrentNoteEvent & 0x0f;
   	    CurrentOctave = 7 - CurrentOctave;	//invert it no division for top octave
   	 }
      } else { // note event, set it up and synthesize
   	 //number of ticks for this note event
   	 NoteDurationCount = Durations[ (CurrentNoteEvent & 0x0f)];	
   	 NoteIndex = (CurrentNoteEvent&0xf0)>>4;
	 
   	 NotePointerIncrement = PitchIncrements[NoteIndex] >> CurrentOctave;
   	 while(NoteDurationCount){
   	    //synthesis loop|PABLIO_MONO

   	    //synthesize bass drum
   	    BassDrumSynthesizer(&BassDrumPointerIncrement,&BassDrumOutput,
	                        &BassDrumIsOn);
	    NoteAndBDOutput = BassDrumOutput;

   	    //FuzzGuitar tone generator
   	    NoteWavePointer += NotePointerIncrement;
   	    WaveINDEX = NoteWavePointer >> 8;	
	    NoteSynthOutput = *(WaveRAM+(WaveINDEX));

   	    //power of two mixing
   	    NoteAndBDOutput += NoteSynthOutput >> 1;
	    //write 8 bit unsigned raw Output to file for 6000 kHz playback sampling rate
	    buffer[0] =  (short)((NoteAndBDOutput - 0x7F)<<8);
	    WriteAudioStream(outStream, buffer, 1);

   	    //scale tick to provide tempo control
   	    OverFlow = TempoCounter;
   	    TempoCounter += 0x0301;
   	    if(TempoCounter < OverFlow){
   	       //OverFlow overflowed so a tick has occurred
   	       if(--BassDrumDurationCount == 0){
   		  //time for new bass drum
   		  BassDrumDurationCount = 0x30;
   		  BassDrumIsOn = 0xFF;
   		  BassDrumPointerIncrement = 0x07FF;
   	       }
   	       //2 tick separation of each note event
   	       if(NoteDurationCount == 2)
   		  NotePointerIncrement = 0;
   	       NoteDurationCount--;
   	    }
      	 }
      }// note event, set it up and synthesize
      //get next script element		
      CurrentNoteEvent = TuneScripts[TuneSelection][ScriptIndex++];	
   } //end of CurrentNoteEvent != 0xff
   CloseAudioStream(outStream);
return 0;
}
static switch_status_t engage_device(portaudio_stream_source_t *source, int restart)
{
	PaStreamParameters inputParameters, outputParameters;
	PaError err;
	int sample_rate = source->rate;
	int codec_ms = source->interval;

	switch_mutex_init(&source->device_lock, SWITCH_MUTEX_NESTED, module_pool);

	if (source->timer.timer_interface) {
		switch_core_timer_sync(&source->timer);
	}

	if (source->audio_stream) {
		return SWITCH_STATUS_SUCCESS;
	}

	if (!switch_core_codec_ready(&source->read_codec)) {
		if (switch_core_codec_init(&source->read_codec,
								   "L16",
								   NULL, sample_rate, codec_ms, 1, SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE, NULL,
								   NULL) != SWITCH_STATUS_SUCCESS) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't load codec?\n");
			return SWITCH_STATUS_FALSE;
		}
	}

	switch_assert(source->read_codec.implementation);

	if (!switch_core_codec_ready(&source->write_codec)) {
		if (switch_core_codec_init(&source->write_codec,
								   "L16",
								   NULL,
								   sample_rate, codec_ms, 1, SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE, NULL, NULL) != SWITCH_STATUS_SUCCESS) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't load codec?\n");
			switch_core_codec_destroy(&source->read_codec);
			return SWITCH_STATUS_FALSE;
		}
	}


	if (!source->timer.timer_interface) {
		if (switch_core_timer_init(&source->timer,
								   source->timer_name, codec_ms, source->read_codec.implementation->samples_per_packet,
								   module_pool) != SWITCH_STATUS_SUCCESS) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "setup timer failed!\n");
			switch_core_codec_destroy(&source->read_codec);
			switch_core_codec_destroy(&source->write_codec);
			return SWITCH_STATUS_FALSE;
		}
	}

	source->read_frame.rate = sample_rate;
	source->read_frame.codec = &source->read_codec;

	switch_mutex_lock(source->device_lock);
	/* LOCKED ************************************************************************************************** */
	inputParameters.device = source->sourcedev;
	inputParameters.channelCount = 1;
	inputParameters.sampleFormat = SAMPLE_TYPE;
	inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultLowInputLatency;
	inputParameters.hostApiSpecificStreamInfo = NULL;
	outputParameters.device = source->sourcedev;
	outputParameters.channelCount = 1;
	outputParameters.sampleFormat = SAMPLE_TYPE;
	outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputParameters.device)->defaultLowOutputLatency;
	outputParameters.hostApiSpecificStreamInfo = NULL;


	err = OpenAudioStream(&source->audio_stream, &inputParameters, NULL, sample_rate, paClipOff, source->read_codec.implementation->samples_per_packet, 0);
	/* UNLOCKED ************************************************************************************************* */
	if (err != paNoError) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error opening audio device retrying\n");
		switch_yield(1000000);
		err = OpenAudioStream(&source->audio_stream, &inputParameters, &outputParameters, sample_rate, paClipOff,
							  source->read_codec.implementation->samples_per_packet, 0);
	}

	switch_mutex_unlock(source->device_lock);
	if (err != paNoError) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't open audio device\n");
		switch_core_codec_destroy(&source->read_codec);
		switch_core_timer_destroy(&source->timer);
		return SWITCH_STATUS_FALSE;
	}


	return SWITCH_STATUS_SUCCESS;
}
Exemple #19
0
int main(int argc, char *argv[])
{
   PABLIO_Stream  *outStream;
   double theta = 0.0;
   double delta = 2.0 * 3.1415 / (double)SAMPLE_RATE;
   double frequency, attenuation = 1.0;
   char scale = '\0';
   int x,y;

   frequency = 440.0; // default frequency
   double power = pow(2., 1./12.); // 12th root of 2
   double pythag = 0.0;
   double cents, oldcents = 0.0;
   switch(argc) {
      case 1: break;
      case 2: if (argv[1][0]=='-') scale = argv[1][1];
              break;
      default:
	      printf("usage: %s [-h(armonic),p(ythagorean)]\n",
		    argv[1]);
	      exit(-1);
   }

   OpenAudioStream(&outStream, SAMPLE_RATE, paFloat32, 
	 PABLIO_WRITE|PABLIO_MONO);

   while(1) {  // synthesize and output samples forever
      for(y= 0; y<26; y++) {
         for(x= 0; x<NUM_FRAMES; x++) { // synthesize a buffer full of samples
            buffer[x] = attenuation * sin(theta);
            theta += frequency * delta;
         }

         // blocking write provides flow control
         WriteAudioStream(outStream, buffer, NUM_FRAMES); 

         cents = 1200. * log(frequency/440.) / log(2.);

         printf("note: %-2s frequency: %7.3f cents: %8.3f step: %7.3f\n",strings[y<13?y:25-y],frequency,cents,cents-oldcents);

         oldcents = cents;

         if (y < 12)
            if (scale == 'h')
               frequency = 440. * harmonics[y+1];
            else if (scale == 'p') {
               pythag = (pythag <= 5 ? pythag + 7 : pythag - 5);
               frequency = 440. * pow(3./2., pythag); // 3/2 to the 7th
               while (frequency > 893.0)
                  frequency /= 2.;
            }
            else
               frequency *= power;
         else if (y > 12 && y < 25)
            if (scale == 'h')
               frequency = 440.0 * harmonics[24-y];
            else if (scale == 'p') {
               pythag = (pythag < 7 ? pythag + 5 : pythag - 7);
               frequency = 440. * pow(3./2., pythag); // 3/2 to the 7th
               while (frequency > 893.0)
                  frequency /= 2.;
            }
            else
               frequency /= power;
      }
   }

   CloseAudioStream(outStream);
}
Exemple #20
0
//Only Arguments:
//First Argument is the choice of which index to use for the array 0-13
int main(int argc, char* argv[])
{
    unsigned char static WWTAB[14][8]= {
        //PIHigh   VolumeInit AddSubPoint PulseWidthRate
        //Vibrato   Delay     DivExp    LinearVolumeAdjust
        {	0xD5,0x1F,0x6D,0x07,0x80,0x04,0x04,0x09},//WWSND0
        {	0x0F,0xFF,0x11,0x07,0x80,0x04,0x04,0x01},//WWSND1
        {	0xFB,0xC8,0x7F,0x07,0x80,0x07,0x01,0x0D},//WWSND2
        {	0x02,0x30,0x01,0x07,0x80,0x04,0x00,0x01},//WWSND3
        {	0x05,0x20,0xc0,0x0f,0x80,0x03,0xf0,0x07},//WWSND4
        {	0x7A,0x76,0x17,0x01,0x76,0x70,0xFF,0xC0},//WWSND5
        {	0x7A,0x76,0x03,0x01,0x76,0x51,0xFF,0x1F},//WWSND6
        {	0x7A,0x76,0x03,0x07,0x17,0x03,0xFF,0x01},//WWSND7
        {	0x03,0x4D,0xFF,0x07,0x43,0x05,0x00,0x03},//WWSND8
        {	0x03,0x7C,0xFF,0x07,0x43,0x08,0x00,0x03},//WWSND9
        {	0x06,0x14,0xFF,0x01,0x80,0x05,0x05,0x05},//WWSNDA
        {	0x02,0xBA,0xFF,0x07,0x80,0x01,0xFF,0x00},//WWSNDB
        {	0x06,0x30,0x6d,0x07,0x80,0x04,0x04,0x09},//WWSNDC
        {	0x0a,0x00,0xff,0x07,0x80,0x04,0x06,0x01} //WWSNDD example generator
    };

    //VariablePointers ;8 TABLE INITIALIZED VARIABLES
    unsigned char PointerIncrementHigh;	//DS	1
    unsigned char Vibrato;		//DS	1 ;AMOUNT OF VIBRATO OFFSET
    unsigned char VolumeInit;		//DS	1
    unsigned char Delay;			//DS	1 ;DELAY WINDOW
    unsigned char AddSubPoint;		//DS	1 ;ADD/SUBTRACT POINT
    unsigned char DivExp;		//DS	1 ;EXPONENTIAL VOLUME ADJUST
    unsigned char PulseWidthRate;	//DS	1 ;PULSE WIDTH RATE
    unsigned char LinearVolumeAdjust;	//DS	1 ;LINEAR VOLUME ADJUST
    //; END OF TABLE INITIALIZED VARIABLES

    unsigned char *VariablePointers[8] = {
        &PointerIncrementHigh,
        &Vibrato,
        &VolumeInit,
        &Delay,
        &AddSubPoint,
        &DivExp,
        &PulseWidthRate,
        &LinearVolumeAdjust
    };

    unsigned short WidthRamp;	//DS	2
    unsigned short Magnitude;	//DS	2
    unsigned  char temp;		//DS	1
    unsigned  char ClientInput;
    unsigned  char DelayCount;

    unsigned short WavePointer,PointerIncrement;
    int i,lw = 0;
    unsigned char DACOutput;
    unsigned short buffer[NUM_FRAMES];
    PABLIO_Stream *outStream;
    PaError result;

    short DIAGDir;

    int NotDone;


    if(argc!=2) {
        printf("%s: number 0-13\n", argv[0]);
        exit(-1);
    }

    //first time initialization
    srand( (unsigned)time( NULL ) );	//for C version

    ClientInput = (unsigned char) atoi (argv[1]);
    for(i =0; i < 8; i++)
        *VariablePointers[i] = WWTAB[ClientInput][i];

    PointerIncrement = PointerIncrementHigh << 8;
    WavePointer = 0x0101;
    Magnitude = (VolumeInit << 8) + VolumeInit;
    WidthRamp = 0x0707;
    NotDone = 1;
    result = OpenAudioStream(&outStream, SAMPLE_RATE, paInt16,
                             PABLIO_WRITE|PABLIO_MONO);

    while(NotDone) {
        if( (WavePointer >> 8) < AddSubPoint ) {
            DIAGDir = -1;
            PointerIncrement -= Vibrato;
        } else { //WavePointer is > AddSubPoint
            DIAGDir = 1;
            PointerIncrement += Vibrato;
        }

        temp = Magnitude >>8;
        if(DivExp < 9)
            temp >>= DivExp;	//power of 2 divide by DivExp
        else {
            if(DivExp > 0x7f)