示例#1
1
文件: example.c 项目: rubyist/tdrum
int main(int argc, char **argv)
{
	SF_INFO sfi;
	SNDFILE *sf;

	sf_count_t nread;
	const size_t nframes = 512;
	float *buf;

	PaStream *stream;
	int err;

	/* Open the input file */
	if (argc < 2)
		DIE("Syntax: %s <filename>\n", argv[0]);
	memset(&sfi, 0, sizeof(sfi));
	if ((sf = sf_open(argv[1], SFM_READ, &sfi)) == NULL)
		DIE("Could not open \"%s\".\n", argv[1]);

	/* Allocate buffer */
	if ((buf = malloc(nframes * sfi.channels * sizeof(float))) == NULL)
		DIE("Could not malloc.");

	/* Initialise PortAudio and open stream for default output device */
	PA_ENSURE( Pa_Initialize() );
	/* Assume that the audio device can handle the input file's sample rate
	   and number of channels */
	PA_ENSURE( Pa_OpenDefaultStream(&stream, 0, sfi.channels, paFloat32, sfi.samplerate,
					paFramesPerBufferUnspecified, NULL, NULL) );
	PA_ENSURE( Pa_StartStream(stream) );

	/* Write file data to stream */
	while ((nread = sf_readf_float(sf, buf, nframes)) > 0)
		PA_ENSURE( Pa_WriteStream(stream, buf, nread) );

	/* Clean up */
	PA_ENSURE( Pa_StopStream(stream) );
	PA_ENSURE( Pa_CloseStream(stream) );
error:
	Pa_Terminate();
	sf_close(sf);
	free(buf);

	return err != paNoError;
}
//recorder input callback
static int recorder(const void *i_buff, void *o_buff, unsigned long frames_per_buffer, 
          const PaStreamCallbackTimeInfo *time_info, PaStreamFlags status_flag, 
          void *i_data)
{
  RecData *data = (RecData*) i_data;
  const SAMPLE *rptr = (const SAMPLE*) i_buff;
  SAMPLE *wptr = &data->recorded_samples[data->frame_idx * NUM_CHANNELS];
  long frames_to_calc;
  int rtrn;
  unsigned long frames_left = data->max_frame_idx - data->frame_idx;
  (void) o_buff; (void) time_info; (void)status_flag; (void) i_data;
  


  if(frames_left < frames_per_buffer){
    frames_to_calc = frames_left;
    rtrn = paComplete;
  }
  else{
    frames_to_calc = frames_per_buffer;
    rtrn = paContinue;
  }


  publ::aud_publ audio_data;
  std_msgs::Int16 i16_audio_data;

  publ::aud_publ the_array;


  int16_t *dat = (int16_t *) i_buff;
  for (int i = 0; i < frames_to_calc; i++){
    printf("%d ", dat[i]);
    i16_audio_data.data = dat[i];
    //audio_data.audio_raw.push_back(i16_audio_data);
    the_array.audio_raw_data.data.push_back(dat[i]);
  }
  printf("---------------------------------------------\n");
    printf("FRAMES: %ld\nSIZE: %lu\n", frames_to_calc, sizeof(i_buff)); 
    if(ENABLE_PLAYBACK)
      err = Pa_WriteStream(o_stream, i_buff, frames_to_calc);
  data->frame_idx += frames_to_calc;
  pub.publish(the_array);
  the_array.audio_raw_data.data.clear();
  return rtrn;
}
示例#3
0
/*-----------------------------------------------------------------------------------------*/
static int TestBadActions( void )
{
    PaStream*           stream = NULL;
    PaError             result;
    PaQaData            myData;
    PaStreamParameters  opp;
    const PaDeviceInfo* info = NULL;

    /* Setup data for synthesis thread. */
    myData.framesLeft = (unsigned long)(SAMPLE_RATE * 100); /* 100 seconds */
    myData.numChannels = 1;
    myData.mode = MODE_OUTPUT;

    opp.device                    = Pa_GetDefaultOutputDevice(); /* Default output. */
    opp.channelCount              = 2;                           /* Stereo output.  */
    opp.hostApiSpecificStreamInfo = NULL;
    opp.sampleFormat              = paFloat32;
    info = Pa_GetDeviceInfo(opp.device);
    opp.suggestedLatency          = info ? info->defaultLowOutputLatency : 0.100;

    if (opp.device != paNoDevice) {
        HOPEFOR(((result = Pa_OpenStream(&stream, NULL, /* Take NULL as input parame-     */
                                         &opp,          /* ters, meaning try only output. */
                                         SAMPLE_RATE, FRAMES_PER_BUFFER,
                                         paClipOff, QaCallback, &myData )) == paNoError));
    }

    HOPEFOR(((result = Pa_StartStream(NULL))    == paBadStreamPtr));
    HOPEFOR(((result = Pa_StopStream(NULL))     == paBadStreamPtr));
    HOPEFOR(((result = Pa_IsStreamStopped(NULL)) == paBadStreamPtr));
    HOPEFOR(((result = Pa_IsStreamActive(NULL)) == paBadStreamPtr));
    HOPEFOR(((result = Pa_CloseStream(NULL))    == paBadStreamPtr));
    HOPEFOR(((result = Pa_SetStreamFinishedCallback(NULL, NULL)) == paBadStreamPtr));
    HOPEFOR(((result = !Pa_GetStreamInfo(NULL))));
    HOPEFOR(((result = Pa_GetStreamTime(NULL))  == 0.0));
    HOPEFOR(((result = Pa_GetStreamCpuLoad(NULL))  == 0.0));
    HOPEFOR(((result = Pa_ReadStream(NULL, NULL, 0))  == paBadStreamPtr));
    HOPEFOR(((result = Pa_WriteStream(NULL, NULL, 0))  == paBadStreamPtr));

    /** @todo test Pa_GetStreamReadAvailable and Pa_GetStreamWriteAvailable */

    if (stream != NULL) Pa_CloseStream(stream);
    return result;
}
示例#4
0
//Final call from receiver ProcessIQData to send audio out
void AudioPA::SendToOutput(CPX *out, int outSamples, float gain, bool mute)
{
	float *outPtr;
	outPtr = outStreamBuffer;
    float temp;

	//Save CPU and don't output anything if mute
	//Note some sound systems may require outputting 0's, if so, then remove this check
	if (mute)
		return;

	const float maxOutput = 0.9999;

	//We may have to skip samples to reduce rate to match audio out, decimate set when we
	//opened stream
    for (int i=0;i<outSamples;i++)
	{
		//PortAudio doesn't have a SetVolume() call like QAudio, so we scale up samples
		//UI returns gain from 0 to 100
		out[i] *= (gain / 100); //1 is full gain

		temp = out[i].real();
        //Cap at -1 to +1 to make sure we don't overdrive
		if (temp > maxOutput)
			temp = maxOutput;
		else if (temp < -maxOutput)
			temp = -maxOutput;
        *outPtr++ = temp;
		temp = out[i].imag();
        //Cap at -1 to +1 to make sure we don't overdrive
		if (temp > maxOutput)
			temp = maxOutput;
		else if (temp < -maxOutput)
			temp = -maxOutput;
        *outPtr++ = temp;
	}

	//Note we use frameCount, not #bytes in outStreamBuffer.  WriteStream knows format
    error = Pa_WriteStream(outStream,outStreamBuffer,outSamples);
}
示例#5
0
int sdr1000_write(float* left_samples,float* right_samples) {
    int rc;
    int i;
    float audio_buffer[SAMPLES_PER_BUFFER*2];

    rc=0;

    // interleave samples
    for(i=0;i<SAMPLES_PER_BUFFER;i++) {
        audio_buffer[i*2]=right_samples[i];
        audio_buffer[(i*2)+1]=left_samples[i];
    }

    //fprintf(stderr,"write available=%ld\n",Pa_GetStreamWriteAvailable(stream));
    rc=Pa_WriteStream(stream,audio_buffer,SAMPLES_PER_BUFFER);
    if(rc!=0) {
        fprintf(stderr,"error writing audio_buffer %s (rc=%d)\n",Pa_GetErrorText(rc),rc);
    }


    return rc;
}
int main( int argc, char * argv[] ) {
	FILE * file = 0;
	size_t size = 0;
	void * data = 0;
	openmpt_module * mod = 0;
	size_t count = 0;
	PaStream * stream = 0;
	PaStreamParameters streamparameters;
	memset( &streamparameters, 0, sizeof( PaStreamParameters ) );
	(void)argc;
	file = fopen( argv[1], "rb" );
	fseek( file, 0, SEEK_END );
	size = ftell( file );
	fseek( file, 0, SEEK_SET );
	data = malloc( size );
	size = fread( data, 1, size, file );
	fclose( file );
	mod = openmpt_module_create_from_memory( data, size, NULL, NULL, NULL );
	free( data );
	Pa_Initialize();
	streamparameters.device = Pa_GetDefaultOutputDevice();
	streamparameters.channelCount = 2;
	streamparameters.sampleFormat = paInt16 | paNonInterleaved;
	streamparameters.suggestedLatency = Pa_GetDeviceInfo( streamparameters.device )->defaultHighOutputLatency;
	Pa_OpenStream( &stream, NULL, &streamparameters, SAMPLERATE, paFramesPerBufferUnspecified, 0, NULL, NULL );
	Pa_StartStream( stream );
	while ( 1 ) {
		count = openmpt_module_read_stereo( mod, SAMPLERATE, BUFFERSIZE, left, right );
		if ( count == 0 ) {
			break;
		}
		Pa_WriteStream( stream, buffers, count );
	}
	Pa_StopStream( stream );
	Pa_CloseStream( stream );
	Pa_Terminate();
	openmpt_module_destroy( mod );
	return 0;
}
OsStatus MpSyncPortAudioStream::writeStream(const void *buffer, unsigned long frames)
{
   OsStatus status = OS_FAILED;

   // copy output frames to meter
   if (m_outputVolumeMeter)
   {
      m_outputVolumeMeter->pushBuffer(buffer, (unsigned int)frames);
   }

   PaError paError = Pa_WriteStream(m_streamId, buffer, frames);

   if (paError == paNoError)
   {
      status = OS_SUCCESS;
   }
   else if (paError == paOutputUnderflowed)
   {
      status = OS_OVERFLOW;
   }

   return status;
}
示例#8
0
/* HTS106_Audio_close: close audio device */
static void HTS106_Audio_close(HTS106_Audio * audio)
{
   if (audio->max_buff_size <= 0)
      return;

   if (audio->buff_size > 0) {
      audio->err = Pa_WriteStream(audio->stream, audio->buff, audio->buff_size);
      if (audio->err != paNoError && audio->err != paOutputUnderflowed)
         HTS106_error(0, "hts_engine: Cannot send datablocks to your output audio device to play waveform.\n");
      audio->buff_size = 0;
   }

   HTS106_free(audio->buff);

   audio->err = Pa_StopStream(audio->stream);
   if (audio->err != paNoError)
      HTS106_error(0, "hts_engine: Cannot stop your output audio device.\n");

   audio->err = Pa_CloseStream(audio->stream);
   if (audio->err != paNoError)
      HTS106_error(0, "hts_engine: Failed to close your output audio device.\n");

   Pa_Terminate();
}
示例#9
0
文件: init.c 项目: andresy/lua---pa
static int pa_stream_writeShort(lua_State *L)
{
  pa_Stream *stream = NULL;
  THShortTensor *data = NULL;
  long nelem = 0;
  PaError err = 0;
  int narg = lua_gettop(L);

  if(narg == 2 && luaT_isudata(L, 1, "pa.Stream") && luaT_isudata(L, 2, "torch.ShortTensor"))
  {
    stream = luaT_toudata(L, 1, "pa.Stream");
    data = luaT_toudata(L, 2, "torch.ShortTensor");
  }
  else
    luaL_error(L, "expected arguments: Stream ShortTensor");

  if(!stream->id)
    luaL_error(L, "attempt to operate on a closed stream");

  nelem = THShortTensor_nElement(data);
  luaL_argcheck(L, (nelem > 0) && (nelem % stream->noutchannel == 0), 2, "invalid data: number of elements must be > 0 and divisible by the number of channels");
  luaL_argcheck(L, stream->outsampleformat & paInt16, 1, "stream does not support short data");

  data = THShortTensor_newContiguous(data);
  err = Pa_WriteStream(stream->id, THShortTensor_data(data), nelem/stream->noutchannel);
  THShortTensor_free(data);

  if(err == paOutputUnderflowed)
    lua_pushboolean(L, 0);
  else if(err == paNoError)
    lua_pushboolean(L, 1);
  else
    pa_checkerror(L, err);

  return 1;
}
示例#10
0
static void sco_packet_handler(uint8_t packet_type, uint8_t * packet, uint16_t size) {
    Pa_WriteStream( stream, &packet[3], size -3);
}
示例#11
0
void* RecieveClientThread(void* data) // recieve udp packets containing message/voice to the other client
{
	struct thread* new_data = data;	

	printf("you are recieving from %s IP address\n", new_data->IPaddr);
	PaStreamParameters outputParam;
	PaStream *stream = NULL;
	char *sampleBlock;
	int i, sockfd, numBytes;
	PaError error;
	struct sockaddr_in servaddr, cliaddr;

	sockfd = socket(AF_INET, SOCK_DGRAM, 0); // make udp socket
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = inet_addr(new_data->IPaddr);
	servaddr.sin_port = htons(new_data->Port);

	bind(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
	fflush(stdout); 
	numBytes = FRAMES_BUFFER * SAMPLE_SIZE * 2;
	sampleBlock = (char *) malloc(numBytes);
	if(sampleBlock == NULL){
		printf("Could not allocate record array.\n");
		exit(1);
	}
	CLEAR(sampleBlock);
 
	printf("Initializing the devices...\n"); 
	error = Pa_Initialize();
	if(error != paNoError) 
		goto errorState;
 
	outputParam.device = Pa_GetDefaultOutputDevice();
  	printf( "Output device # %d.\n", outputParam.device );
	outputParam.channelCount = 2;
	outputParam.sampleFormat = paFloat32;
	outputParam.suggestedLatency = Pa_GetDeviceInfo( outputParam.device )->defaultHighOutputLatency;
	outputParam.hostApiSpecificStreamInfo = NULL;	
 
	error = Pa_OpenStream(&stream, NULL, &outputParam, SAMPLE_RATE, FRAMES_BUFFER, paClipOff, NULL, NULL );
  
	if( error != paNoError ) 
		goto errorState;
 
	error = Pa_StartStream( stream );
	if( error != paNoError ) 
		goto errorState;

	printf("The client is talking to you\n"); 
	fflush(stdout);

	while(1){
		recvfrom(sockfd, sampleBlock, 4096, 0, NULL, NULL); // recieve packet containing voice data from the other client
		error = Pa_WriteStream(stream, sampleBlock, FRAMES_BUFFER);
 		if(error && UNDERFLOW) 
			goto exitState;
	}

	error = Pa_StopStream(stream);
	if(error != paNoError) 
		goto errorState;
 
	CLEAR(sampleBlock);
	free(sampleBlock);
	Pa_Terminate();
	return 0;
 
exitState:
	if(stream){
		Pa_AbortStream(stream);
		Pa_CloseStream(stream);
	}
	free(sampleBlock);
	Pa_Terminate();
	if(error & paOutputUnderflow)
		fprintf(stderr, "Output Underflow.\n");
	return (void*)-2;
 
errorState:
	if(stream) {
		Pa_AbortStream(stream);
		Pa_CloseStream(stream);
	}
	free(sampleBlock);
	Pa_Terminate();
	fprintf(stderr, "An error occured while using the portaudio stream\n");
	fprintf(stderr, "Error number: %d\n", error);
	fprintf(stderr, "Error message: %s\n", Pa_GetErrorText(error));
	return (void*)-1;

}
void PA_AudioIO::write(SAMPLE* input){
    //Expects interleaved audio. Frame size is NOT the block size.
    PaError err = Pa_WriteStream(m_Stream, input, m_frameSize);
    if(err != paNoError)
        Pa_ErrorOccurred(err);
}
int main(void)
{
    PaStreamParameters outputParameters;
    PaStream *stream;
    PaError err;
    TestData data;
    float writeBuffer[ FRAMES_PER_BUFFER * 2 ];
    
    printf("PortAudio Test: check that stopping stream plays out all queued samples. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER);

    InitTestSignalGenerator( &data );
    
    err = Pa_Initialize();
    if( err != paNoError ) goto error;

    outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
    outputParameters.channelCount = 2;       /* stereo output */
    outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */
    outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency;
    outputParameters.hostApiSpecificStreamInfo = NULL;

/* test paComplete ---------------------------------------------------------- */

    ResetTestSignalGenerator( &data );

    err = Pa_OpenStream(
              &stream,
              NULL, /* no input */
              &outputParameters,
              SAMPLE_RATE,
              FRAMES_PER_BUFFER,
              paClipOff,      /* we won't output out of range samples so don't bother clipping them */
              TestCallback1,
              &data );
    if( err != paNoError ) goto error;

    err = Pa_StartStream( stream );
    if( err != paNoError ) goto error;


    printf("\nPlaying 'tone-blip' %d times using callback, stops by returning paComplete from callback.\n", NUM_REPEATS );
    printf("If final blip is not intact, callback+paComplete implementation may be faulty.\n\n" );

    while( (err = Pa_IsStreamActive( stream )) == 1 )
        Pa_Sleep( 5 );

    if( err != 0 ) goto error;

    
    err = Pa_StopStream( stream );
    if( err != paNoError ) goto error;

    err = Pa_CloseStream( stream );
    if( err != paNoError ) goto error;

    Pa_Sleep( 500 );

/* test Pa_StopStream() with callback --------------------------------------- */

    ResetTestSignalGenerator( &data );

    testCallback2Finished = 0;
    
    err = Pa_OpenStream(
              &stream,
              NULL, /* no input */
              &outputParameters,
              SAMPLE_RATE,
              FRAMES_PER_BUFFER,
              paClipOff,      /* we won't output out of range samples so don't bother clipping them */
              TestCallback2,
              &data );
    if( err != paNoError ) goto error;

    err = Pa_StartStream( stream );
    if( err != paNoError ) goto error;


    printf("\nPlaying 'tone-blip' %d times using callback, stops by calling Pa_StopStream.\n", NUM_REPEATS );
    printf("If final blip is not intact, callback+Pa_StopStream implementation may be faulty.\n\n" );

    /* note that polling a volatile flag is not a good way to synchronise with
        the callback, but it's the best we can do portably. */
    while( !testCallback2Finished )
        Pa_Sleep( 2 );

    err = Pa_StopStream( stream );
    if( err != paNoError ) goto error;
    

    err = Pa_CloseStream( stream );
    if( err != paNoError ) goto error;

    Pa_Sleep( 500 );

/* test Pa_StopStream() with Pa_WriteStream --------------------------------- */

    ResetTestSignalGenerator( &data );

    err = Pa_OpenStream(
              &stream,
              NULL, /* no input */
              &outputParameters,
              SAMPLE_RATE,
              FRAMES_PER_BUFFER,
              paClipOff,      /* we won't output out of range samples so don't bother clipping them */
              NULL, /* no callback, use blocking API */
              NULL ); /* no callback, so no callback userData */
    if( err != paNoError ) goto error;

    err = Pa_StartStream( stream );
    if( err != paNoError ) goto error;


    printf("\nPlaying 'tone-blip' %d times using Pa_WriteStream, stops by calling Pa_StopStream.\n", NUM_REPEATS );
    printf("If final blip is not intact, Pa_WriteStream+Pa_StopStream implementation may be faulty.\n\n" );

    do{
        GenerateTestSignal( &data, writeBuffer, FRAMES_PER_BUFFER );
        err = Pa_WriteStream( stream, writeBuffer, FRAMES_PER_BUFFER );
        if( err != paNoError ) goto error;
        
    }while( !IsTestSignalFinished( &data ) );

    err = Pa_StopStream( stream );
    if( err != paNoError ) goto error;
    

    err = Pa_CloseStream( stream );
    if( err != paNoError ) goto error;

/* -------------------------------------------------------------------------- */
    
    Pa_Terminate();
    printf("Test finished.\n");
    
    return err;
    
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 err;
}
示例#14
0
int main(void)
{
    PaStreamParameters outputParameters;
    PaStream *stream;
    PaError err;
    float buffer[FRAMES_PER_BUFFER][2]; /* stereo output buffer */
    float sine[TABLE_SIZE]; /* sine wavetable */
    int left_phase = 0;
    int right_phase = 0;
    int left_inc = 1;
    int right_inc = 3; /* higher pitch so we can distinguish left and right. */
    int i, j, k;
    int bufferCount;

    
    printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER);
    
    /* initialise sinusoidal wavetable */
    for( i=0; i<TABLE_SIZE; i++ )
    {
        sine[i] = (float) sin( ((double)i/(double)TABLE_SIZE) * M_PI * 2. );
    }

    
    err = Pa_Initialize();
    if( err != paNoError ) goto error;

    outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
    outputParameters.channelCount = 2;       /* stereo output */
    outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */
    outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency;
    outputParameters.hostApiSpecificStreamInfo = NULL;

    err = Pa_OpenStream(
              &stream,
              NULL, /* no input */
              &outputParameters,
              SAMPLE_RATE,
              FRAMES_PER_BUFFER,
              paClipOff,      /* we won't output out of range samples so don't bother clipping them */
              NULL, /* no callback, use blocking API */
              NULL ); /* no callback, so no callback userData */
    if( err != paNoError ) goto error;


    printf( "Play 3 times, higher each time.\n" );
    
    for( k=0; k < 3; ++k )
    {
        err = Pa_StartStream( stream );
        if( err != paNoError ) goto error;

        printf("Play for %d seconds.\n", NUM_SECONDS );

        bufferCount = ((NUM_SECONDS * SAMPLE_RATE) / FRAMES_PER_BUFFER);

        for( i=0; i < bufferCount; i++ )
        {
            for( j=0; j < FRAMES_PER_BUFFER; j++ )
            {
                buffer[j][0] = sine[left_phase];  /* left */
                buffer[j][1] = sine[right_phase];  /* right */
                left_phase += left_inc;
                if( left_phase >= TABLE_SIZE ) left_phase -= TABLE_SIZE;
                right_phase += right_inc;
                if( right_phase >= TABLE_SIZE ) right_phase -= TABLE_SIZE;
            }

            err = Pa_WriteStream( stream, buffer, FRAMES_PER_BUFFER );
            if( err != paNoError ) goto error;
        }   

        err = Pa_StopStream( stream );
        if( err != paNoError ) goto error;

        ++left_inc;
        ++right_inc;

        Pa_Sleep( 1000 );
    }

    err = Pa_CloseStream( stream );
    if( err != paNoError ) goto error;

    Pa_Terminate();
    printf("Test finished.\n");
    
    return err;
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 err;
}
示例#15
0
void paSoundFeedVoiceData(unsigned char* pSound, long lBytes)
{
	Pa_WriteStream(stream, (void*) pSound, (unsigned long) lBytes / 4);
}
示例#16
0
文件: Stream.cpp 项目: Zethes/CGUL
_CGUL_EXPORT CGUL::SInt32 CGUL::PortAudio::Stream::Write(CGUL::Float32* buffer, UInt64 frames)
{
    return (SInt32)Pa_WriteStream(stream, (const void*)buffer, frames);
}
示例#17
0
int main(void)
{
    PaStreamParameters outputParameters;
    PaStream *stream;
    PaError err;
    float buffer[FRAMES_PER_BUFFER][2]; /* stereo output buffer */
    float sine[TABLE_SIZE]; /* sine wavetable */
    int left_phase = 0;
    int right_phase = 0;
    int left_inc = 1;
    int right_inc = 3; /* higher pitch so we can distinguish left and right. */
    int i, j;
    int bufferCount;
    const int   framesBy2  = FRAMES_PER_BUFFER >> 1;
    const float framesBy2f = (float) framesBy2 ;


    printf( "PortAudio Test: output silence, followed by one buffer of a ramped sine wave. SR = %d, BufSize = %d\n",
            SAMPLE_RATE, FRAMES_PER_BUFFER);

    /* initialise sinusoidal wavetable */
    for( i=0; i<TABLE_SIZE; i++ )
    {
        sine[i] = (float) sin( ((double)i/(double)TABLE_SIZE) * M_PI * 2. );
    }


    err = Pa_Initialize();
    if( err != paNoError ) goto error;

    outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
    outputParameters.channelCount = 2;       /* stereo output */
    outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */
    outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency * 5;
    outputParameters.hostApiSpecificStreamInfo = NULL;

    /* open the stream */
    err = Pa_OpenStream(
              &stream,
              NULL, /* no input */
              &outputParameters,
              SAMPLE_RATE,
              FRAMES_PER_BUFFER,
              paClipOff,      /* we won't output out of range samples so don't bother clipping them */
              NULL, /* no callback, use blocking API */
              NULL ); /* no callback, so no callback userData */
    if( err != paNoError ) goto error;

    /* start the stream */
    err = Pa_StartStream( stream );
    if( err != paNoError ) goto error;

    printf("Playing %d seconds of silence followed by one buffer of a ramped sinusoid.\n", NUM_SECONDS );

    bufferCount = ((NUM_SECONDS * SAMPLE_RATE) / FRAMES_PER_BUFFER);

    /* clear buffer */
    for( j=0; j < FRAMES_PER_BUFFER; j++ )
    {
        buffer[j][0] = 0;  /* left */
        buffer[j][1] = 0;  /* right */
    }
    /* play the silent buffer a bunch o' times */
    for( i=0; i < bufferCount; i++ )
    {
        err = Pa_WriteStream( stream, buffer, FRAMES_PER_BUFFER );
        if( err != paNoError ) goto error;
    }
    /* play a non-silent buffer once */
    for( j=0; j < FRAMES_PER_BUFFER; j++ )
    {
        float ramp = 1;
        if( j < framesBy2 )
            ramp = j / framesBy2f;
        else
            ramp = (FRAMES_PER_BUFFER - j) / framesBy2f ;

        buffer[j][0] = sine[left_phase] * ramp;  /* left */
        buffer[j][1] = sine[right_phase] * ramp;  /* right */
        left_phase += left_inc;
        if( left_phase >= TABLE_SIZE ) left_phase -= TABLE_SIZE;
        right_phase += right_inc;
        if( right_phase >= TABLE_SIZE ) right_phase -= TABLE_SIZE;
    }
    err = Pa_WriteStream( stream, buffer, FRAMES_PER_BUFFER );
    if( err != paNoError ) goto error;

    /* stop stream, close, and terminate */
    err = Pa_StopStream( stream );
    if( err != paNoError ) goto error;

    err = Pa_CloseStream( stream );
    if( err != paNoError ) goto error;

    Pa_Terminate();
    printf("Test finished.\n");

    return err;
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 err;
}
示例#18
0
sample_type sound_save_array(LVAL sa, long n, SF_INFO *sf_info, 
        SNDFILE *sndfile, float *buf, long *ntotal, PaStream *audio_stream)
{
    long i, chans;
    float *float_bufp;
    sound_state_type state;
    double start_time = HUGE_VAL;
    LVAL sa_copy;
    long debug_unit;    /* print messages at intervals of this many samples */
    long debug_count;   /* next point at which to print a message */
    sample_type max_sample = 0.0F;
    sample_type threshold = 0.0F;
    /*    cvtfn_type cvtfn; jlh */

    *ntotal = 0;

    /* THE ALGORITHM: first merge floating point samples from N channels
     * into consecutive multi-channel frames in buf.  Then, treat buf
     * as just one channel and use one of the cvt_to_* functions to
     * convert the data IN PLACE in the buffer (this is ok because the
     * converted data will never take more space than the original 32-bit
     * floats, so the converted data will not overwrite any floats before
     * the floats are converted
     */

    /* if snd_expr was simply a symbol, then sa now points to
        a shared sound_node.  If we read samples from it, then
        the sounds bound to the symbol will be destroyed, so
        copy it first.  If snd_expr was a real expression that
        computed a new value, then the next garbage collection
        will reclaim the sound array.  See also sound_save_sound()
    */

    chans = getsize(sa);
    if (chans > MAX_SND_CHANNELS) {
        xlerror("sound_save: too many channels", sa);
        free(buf);
        sf_close(sndfile);
    }
    xlprot1(sa);
    sa_copy = newvector(chans);
    xlprot1(sa_copy);

    /* Why do we copy the array into an xlisp array instead of just
     * the state[i] array? Because some of these sounds may reference
     * the lisp heap. We must put the sounds in an xlisp array so that
     * the gc will find and mark them. xlprot1(sa_copy) makes the array
     * visible to gc.
     */
    for (i = 0; i < chans; i++) {
        sound_type s = getsound(getelement(sa, i));
        setelement(sa_copy, i, cvsound(sound_copy(s)));
    }
    sa = sa_copy;	/* destroy original reference to allow GC */

    state = (sound_state_type) malloc(sizeof(sound_state_node) * chans);
    for (i = 0; i < chans; i++) {
        state[i].sound = getsound(getelement(sa, i));
        state[i].scale = state[i].sound->scale;
D       nyquist_printf("save scale factor %ld = %g\n", i, state[i].scale);
        state[i].terminated = false;
        state[i].cnt = 0;   /* force a fetch */
        start_time = min(start_time, state[i].sound->t0);
    }

    for (i = 0; i < chans; i++) {
        if (state[i].sound->t0 > start_time)
            sound_prepend_zeros(state[i].sound, start_time);
    }

    debug_unit = debug_count = (long) max(sf_info->samplerate, 10000.0);

    sound_frames = 0;
    sound_srate = sf_info->samplerate;
    while (n > 0) {
        /* keep the following information for each sound:
            has it terminated?
            pointer to samples
            number of samples remaining in block
           scan to find the minimum remaining samples and
           output that many in an inner loop.  Stop outer
           loop if all sounds have terminated
         */
        int terminated = true;
        int togo = n;
        int j;

        oscheck();

        for (i = 0; i < chans; i++) {
            if (state[i].cnt == 0) {
                if (sndwrite_trace) {
                    nyquist_printf("CALLING SOUND_GET_NEXT ON CHANNEL %ld (%lx)\n",
				   i, (unsigned long) state[i].sound); /* jlh 64 bit issue */
                    sound_print_tree(state[i].sound);
                }
                state[i].ptr = sound_get_next(state[i].sound,
                                   &(state[i].cnt))->samples;
                if (sndwrite_trace) {
                    nyquist_printf("RETURNED FROM CALL TO SOUND_GET_NEXT ON CHANNEL %ld\n", i);
                }
                if (state[i].ptr == zero_block->samples) {
                    state[i].terminated = true;
                }
            }
            if (!state[i].terminated) terminated = false;
            togo = min(togo, state[i].cnt);
        }

        if (terminated) break;

        float_bufp = (float *) buf;
        if (is_pcm(sf_info)) {
            for (j = 0; j < togo; j++) {
                for (i = 0; i < chans; i++) {
                    float s = (float) (*(state[i].ptr++) * (float) state[i].scale);
                    COMPUTE_MAXIMUM_AND_WRAP(s);
                    *float_bufp++ = s;
                }
            }
        } else {
            for (j = 0; j < togo; j++) {
                for (i = 0; i < chans; i++) {
                    float s = (float) (*(state[i].ptr++) * (float) state[i].scale);
                    COMPUTE_MAXIMUM();
                    *float_bufp++ = s;
                }
            }
        }
        /* Here we have interleaved floats. Before converting to the sound
           file format, call PortAudio to play them. */
        if (audio_stream) {
            PaError err = Pa_WriteStream(audio_stream, buf, togo);
            if (err) {
                printf("Pa_WriteStream error %d\n", err);
            }
            sound_frames += togo;
        }
        if (sndfile) sf_writef_float(sndfile, buf, togo);

        n -= togo;
        for (i = 0; i < chans; i++) {
            state[i].cnt -= togo;
        }
        *ntotal += togo;
        if (*ntotal > debug_count) {
            gprintf(TRANS, " %ld ", *ntotal);
            fflush(stdout);
            debug_count += debug_unit;
        }
    }
    gprintf(TRANS, "total samples: %ld x %ld channels\n",
           *ntotal, chans);

    /* references to sounds are shared by sa_copy and state[].
     * here, we dispose of state[], allowing GC to do the
     * sound_unref call that frees the sounds. (Freeing them now
     * would be a bug.)
     */
    free(state);
    xlpop();
    return max_sample;
}
示例#19
0
sample_type sound_save_sound(LVAL s_as_lval, long n, SF_INFO *sf_info, 
        SNDFILE *sndfile, float *buf, long *ntotal, PaStream *audio_stream)
{
    long blocklen;
    sound_type s;
    int i;
    sample_type *samps;
    long debug_unit;    /* print messages at intervals of this many samples */
    long debug_count;   /* next point at which to print a message */
    sample_type max_sample = 0.0F;
    sample_type threshold = 0.0F;
    /* jlh    cvtfn_type cvtfn; */
    *ntotal = 0;
    /* if snd_expr was simply a symbol, then s now points to
        a shared sound_node.  If we read samples from it, then
        the sound bound to the symbol will be destroyed, so
        copy it first.  If snd_expr was a real expression that
        computed a new value, then the next garbage collection
        will reclaim the sound_node.  We need to make the new
        sound reachable by the garbage collector to that any
        lisp data reachable from the sound do not get collected.
        To make the sound reachable, we need to allocate a node,
        and the GC might run, so we need to protect the OLD s
        but then make it unreachable.
        We will let the GC collect the sound in the end.
    */
    xlprot1(s_as_lval);
    s = sound_copy(getsound(s_as_lval));
    s_as_lval = cvsound(s);	/* destroys only ref. to original */

    /* for debugging */
/*    printing_this_sound = s;*/


    debug_unit = debug_count = (long) max(sf_info->samplerate, 10000.0);

    sound_frames = 0;
    sound_srate = sf_info->samplerate;

    while (n > 0) {
        long togo;
        sample_block_type sampblock = sound_get_next(s, &blocklen);
        oscheck();
#ifdef SNAPSHOTS
        stdputstr(".");
        if (sound_created_flag) {
            stdputstr("SNAPSHOT: ");
            sound_print_tree(printing_this_sound);
            sound_created_flag = false;
        }
        fflush(stdout);
#endif
        if (sampblock == zero_block || blocklen == 0) {
            break;
        }
        togo = min(blocklen, n);
        if (s->scale != 1) { /* copy/scale samples into buf */
            for (i = 0; i < togo; i++) {
                buf[i] = s->scale * sampblock->samples[i];
            }
            samps = buf;
        } else {
            samps = sampblock->samples;
        }
        if (is_pcm(sf_info)) {
            for (i = 0; i < togo; i++) {
                sample_type s = samps[i];
                COMPUTE_MAXIMUM_AND_WRAP(samps[i]);
            }
        } else {
            for (i = 0; i < togo; i++) {
                sample_type s = samps[i];
                COMPUTE_MAXIMUM();
            }
        }
        if (sndfile) {
            sf_writef_float(sndfile, samps, togo);
        }
        if (audio_stream) {
            Pa_WriteStream(audio_stream, samps, togo);
            sound_frames += togo;
        }

        n -= togo;
        *ntotal += togo;
        if (*ntotal > debug_count) {
            gprintf(TRANS, " %ld ", *ntotal);
            fflush(stdout);
            debug_count += debug_unit;
        }
    }
    gprintf(TRANS, "\ntotal samples: %ld\n", *ntotal);
    xlpop();
    return max_sample;
}
示例#20
0
_JATTA_EXPORT Jatta::SInt32 Jatta::PortAudio::Stream::Write(Jatta::Float32* buffer, UInt64 frames)
{
    return (SInt32)Pa_WriteStream(stream, (const void*)buffer, frames);
}
int main(void)
{
    PaStreamParameters inputParameters, outputParameters;
    PaStream *stream = NULL;
    PaError err;
    char *sampleBlock;
    int i;
    int numBytes;
    
    
    printf("patest_read_write_wire.c\n"); fflush(stdout);

    numBytes = FRAMES_PER_BUFFER * NUM_CHANNELS * SAMPLE_SIZE ;
    sampleBlock = (char *) malloc( numBytes );
    if( sampleBlock == NULL )
    {
        printf("Could not allocate record array.\n");
        exit(1);
    }
    CLEAR( sampleBlock );

    err = Pa_Initialize();
    if( err != paNoError ) goto error;

    inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */
    printf( "Input device # %d.\n", inputParameters.device );
    printf( "Input LL: %g s\n", Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency );
    printf( "Input HL: %g s\n", Pa_GetDeviceInfo( inputParameters.device )->defaultHighInputLatency );
    inputParameters.channelCount = NUM_CHANNELS;
    inputParameters.sampleFormat = PA_SAMPLE_TYPE;
    inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultHighInputLatency ;
    inputParameters.hostApiSpecificStreamInfo = NULL;

    outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
    printf( "Output device # %d.\n", outputParameters.device );
    printf( "Output LL: %g s\n", Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency );
    printf( "Output HL: %g s\n", Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency );
    outputParameters.channelCount = NUM_CHANNELS;
    outputParameters.sampleFormat = PA_SAMPLE_TYPE;
    outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency;
    outputParameters.hostApiSpecificStreamInfo = NULL;

    /* -- setup -- */

   err = Pa_OpenStream(
              &stream,
              &inputParameters,
              &outputParameters,
              SAMPLE_RATE,
              FRAMES_PER_BUFFER,
              paClipOff,      /* we won't output out of range samples so don't bother clipping them */
              NULL, /* no callback, use blocking API */
              NULL ); /* no callback, so no callback userData */
    if( err != paNoError ) goto error;

    err = Pa_StartStream( stream );
    if( err != paNoError ) goto error;
    printf("Wire on. Will run %d seconds.\n", NUM_SECONDS); fflush(stdout);

    for( i=0; i<(NUM_SECONDS*SAMPLE_RATE)/FRAMES_PER_BUFFER; ++i )
    {
       err = Pa_WriteStream( stream, sampleBlock, FRAMES_PER_BUFFER );
       if( err && CHECK_UNDERFLOW ) goto xrun;
       err = Pa_ReadStream( stream, sampleBlock, FRAMES_PER_BUFFER );
       if( err && CHECK_OVERFLOW ) goto xrun;
    }
    err = Pa_StopStream( stream );
    if( err != paNoError ) goto error;

    CLEAR( sampleBlock );
/*
    err = Pa_StartStream( stream );
    if( err != paNoError ) goto error;
    printf("Wire on. Interrupt to stop.\n"); fflush(stdout);

    while( 1 )
    {
       err = Pa_WriteStream( stream, sampleBlock, FRAMES_PER_BUFFER );
       if( err ) goto xrun;
       err = Pa_ReadStream( stream, sampleBlock, FRAMES_PER_BUFFER );
       if( err ) goto xrun;
    }
    err = Pa_StopStream( stream );
    if( err != paNoError ) goto error;

    Pa_CloseStream( stream );
*/
    free( sampleBlock );

    Pa_Terminate();
    return 0;

xrun:
    if( stream ) {
       Pa_AbortStream( stream );
       Pa_CloseStream( stream );
    }
    free( sampleBlock );
    Pa_Terminate();
    if( err & paInputOverflow )
       fprintf( stderr, "Input Overflow.\n" );
    if( err & paOutputUnderflow )
       fprintf( stderr, "Output Underflow.\n" );
    return -2;

error:
    if( stream ) {
       Pa_AbortStream( stream );
       Pa_CloseStream( stream );
    }
    free( sampleBlock );
    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;
}
示例#22
0
    int chn = d.channels;
    if (chn == 6 || chn == 8) {
		float *audio_buffer = (float *)d.data.data();
		int size_per_chn = d.data.size() >> 2;
        for (int i = 0 ; i < size_per_chn; i += chn) {
            float tmp = audio_buffer[i+2];
            audio_buffer[i+2] = audio_buffer[i+4];
            audio_buffer[i+4] = tmp;
            tmp = audio_buffer[i+3];
            audio_buffer[i+3] = audio_buffer[i+5];
            audio_buffer[i+5] = tmp;
        }
    }
#endif
#endif //KNOW_WHY
    PaError err = Pa_WriteStream(d.stream, d.data.data(), d.data.size()/audioFormat().channels()/audioFormat().bytesPerSample());
    if (err == paUnanticipatedHostError) {
        qWarning("Write portaudio stream error: %s", Pa_GetErrorText(err));
		return false;
    }
	return true;
}
//TODO: what about planar, int8, int24 etc that FFmpeg or Pa not support?
static int toPaSampleFormat(AudioFormat::SampleFormat format)
{
    switch (format) {
    case AudioFormat::SampleFormat_Unsigned8:
        return paUInt8;
    case AudioFormat::SampleFormat_Signed16:
        return paInt16;
    case AudioFormat::SampleFormat_Signed32:
示例#23
0
//INSERT NEW CODE HERE==========================================================
int main (void)
{
	 PaStream *stream = NULL;
	int i;
	PaError err;
	char * sampleBlock ;
	
	/* -- initialize PortAudio -- */
	err = Pa_Initialize();
	 PaStreamParameters inputParameters, outputParameters;
	if( err != paNoError ) goto error;
	
	/* -- setup input and output -- */
	inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */
	inputParameters.channelCount = NUM_CHANNELS;
	inputParameters.sampleFormat = PA_SAMPLE_TYPE;
	inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultHighInputLatency ;
	inputParameters.hostApiSpecificStreamInfo = NULL;
	outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
	outputParameters.channelCount = NUM_CHANNELS;
	outputParameters.sampleFormat = PA_SAMPLE_TYPE;
	outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency;
	outputParameters.hostApiSpecificStreamInfo = NULL;
	
	
	/* -- setup stream -- */
	err = Pa_OpenStream(
	&stream,
	&inputParameters,
	&outputParameters,
	SAMPLE_RATE,
	FRAMES_PER_BUFFER,
	paClipOff, /* we won't output out of range samples so don't bother clipping them */
	NULL, /* no callback, use blocking API */
	NULL ); /* no callback, so no callback userData */
	if( err != paNoError ) goto error;
	/* -- start stream -- */
	int errx;
	errx = Pa_StartStream( stream );
	if( err != paNoError ) goto error;
	printf("Wire on. Will run one minute.\n"); fflush(stdout);
	/* -- Here's the loop where we pass data from input to output -- */
	for( i=0; i<(60*SAMPLE_RATE)/FRAMES_PER_BUFFER; ++i )
	{
	errx = Pa_WriteStream( stream, sampleBlock, FRAMES_PER_BUFFER );
	if( errx ) goto xrun;
	errx = Pa_ReadStream( stream, sampleBlock, FRAMES_PER_BUFFER );
	if( errx ) goto xrun;
	}
	/* -- Now we stop the stream -- */
	errx = Pa_StopStream( stream );
	if( errx != paNoError ) goto error;
	/* -- don't forget to cleanup! -- */
	errx = Pa_CloseStream( stream );
	if( errx != paNoError ) goto error;
	Pa_Terminate();
	return 0;
xrun:
  if( stream ) {
  Pa_AbortStream( stream );
  Pa_CloseStream( stream );
  }
 free( sampleBlock );
  Pa_Terminate();
  if( err & paInputOverflow )
  fprintf( stderr, "Input Overflow.\n" );
  if( err & paOutputUnderflow )
  fprintf( stderr, "Output Underflow.\n" );
  return -2;
error:
  if( stream ) {
  Pa_AbortStream( stream );
  Pa_CloseStream( stream );
  }
  free( sampleBlock );
  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;
 }
示例#24
0
int pa_send_dacs(void)
{
    t_sample *fp;
    float *fp2, *fp3;
    float *conversionbuf;
    int j, k;
    int rtnval =  SENDDACS_YES;
#ifndef FAKEBLOCKING
    double timebefore;
#endif /* FAKEBLOCKING */
    if (!sys_inchannels && !sys_outchannels || !pa_stream)
        return (SENDDACS_NO);
    conversionbuf = (float *)alloca((sys_inchannels > sys_outchannels?
        sys_inchannels:sys_outchannels) * DEFDACBLKSIZE * sizeof(float));

#ifdef FAKEBLOCKING
    if (!sys_inchannels)    /* if no input channels sync on output */
    {
#ifdef THREADSIGNAL
        pthread_mutex_lock(&pa_mutex);
#endif
        while (sys_ringbuf_getwriteavailable(&pa_outring) <
            (long)(sys_outchannels * DEFDACBLKSIZE * sizeof(float)))
        {
            rtnval = SENDDACS_SLEPT;
#ifdef THREADSIGNAL
            pthread_cond_wait(&pa_sem, &pa_mutex);
#else
#ifdef _WIN32
            Sleep(1);
#else
            usleep(1000);
#endif /* _WIN32 */
#endif /* THREADSIGNAL */
        }
#ifdef THREADSIGNAL
        pthread_mutex_unlock(&pa_mutex);
#endif
    }
        /* write output */
    if (sys_outchannels)
    {
        for (j = 0, fp = sys_soundout, fp2 = conversionbuf;
            j < sys_outchannels; j++, fp2++)
                for (k = 0, fp3 = fp2; k < DEFDACBLKSIZE;
                    k++, fp++, fp3 += sys_outchannels)
                        *fp3 = *fp;
        sys_ringbuf_write(&pa_outring, conversionbuf,
            sys_outchannels*(DEFDACBLKSIZE*sizeof(float)), pa_outbuf);
    }
    if (sys_inchannels)    /* if there is input sync on it */
    {
#ifdef THREADSIGNAL
        pthread_mutex_lock(&pa_mutex);
#endif
        while (sys_ringbuf_getreadavailable(&pa_inring) <
            (long)(sys_inchannels * DEFDACBLKSIZE * sizeof(float)))
        {
            rtnval = SENDDACS_SLEPT;
#ifdef THREADSIGNAL
            pthread_cond_wait(&pa_sem, &pa_mutex);
#else
#ifdef _WIN32
            Sleep(1);
#else
            usleep(1000);
#endif /* _WIN32 */
#endif /* THREADSIGNAL */
        }
#ifdef THREADSIGNAL
        pthread_mutex_unlock(&pa_mutex);
#endif
    }
    if (sys_inchannels)
    {
        sys_ringbuf_read(&pa_inring, conversionbuf,
            sys_inchannels*(DEFDACBLKSIZE*sizeof(float)), pa_inbuf);
        for (j = 0, fp = sys_soundin, fp2 = conversionbuf;
            j < sys_inchannels; j++, fp2++)
                for (k = 0, fp3 = fp2; k < DEFDACBLKSIZE;
                    k++, fp++, fp3 += sys_inchannels)
                        *fp = *fp3;
    }

#else /* FAKEBLOCKING */
    timebefore = sys_getrealtime();
        /* write output */
    if (sys_outchannels)
    {
        if (!pa_started)
        {
            memset(conversionbuf, 0,
                sys_outchannels * DEFDACBLKSIZE * sizeof(float));
            for (j = 0; j < pa_nbuffers-1; j++)
                Pa_WriteStream(pa_stream, conversionbuf, DEFDACBLKSIZE);
        }
        for (j = 0, fp = sys_soundout, fp2 = conversionbuf;
            j < sys_outchannels; j++, fp2++)
                for (k = 0, fp3 = fp2; k < DEFDACBLKSIZE;
                    k++, fp++, fp3 += sys_outchannels)
                        *fp3 = *fp;
        Pa_WriteStream(pa_stream, conversionbuf, DEFDACBLKSIZE);
    }

    if (sys_inchannels)
    {
        Pa_ReadStream(pa_stream, conversionbuf, DEFDACBLKSIZE);
        for (j = 0, fp = sys_soundin, fp2 = conversionbuf;
            j < sys_inchannels; j++, fp2++)
                for (k = 0, fp3 = fp2; k < DEFDACBLKSIZE;
                    k++, fp++, fp3 += sys_inchannels)
                        *fp = *fp3;
    }
    if (sys_getrealtime() - timebefore > 0.002)
    {
        rtnval = SENDDACS_SLEPT;
    }
#endif /* FAKEBLOCKING */
    pa_started = 1;

    memset(sys_soundout, 0, DEFDACBLKSIZE*sizeof(t_sample)*sys_outchannels);
    return (rtnval);
}
示例#25
0
int main(void)
{
    PaStreamParameters inputParameters, outputParameters;
    PaStream *stream;
    PaError err;
    SAMPLE *recordedSamples;
    int i;
    int totalFrames;
    int numSamples;
    int numBytes;
    SAMPLE max, average, val;
    
    
    printf("patest_read_record.c\n"); fflush(stdout);

    totalFrames = NUM_SECONDS * SAMPLE_RATE; /* Record for a few seconds. */
    numSamples = totalFrames * NUM_CHANNELS;

    numBytes = numSamples * sizeof(SAMPLE);
    recordedSamples = (SAMPLE *) malloc( numBytes );
    if( recordedSamples == NULL )
    {
        printf("Could not allocate record array.\n");
        exit(1);
    }
    for( i=0; i<numSamples; i++ ) recordedSamples[i] = 0;

    err = Pa_Initialize();
    if( err != paNoError ) goto error;

    inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */
    if (inputParameters.device == paNoDevice) {
      fprintf(stderr,"Error: No default input device.\n");
      goto error;
    }
    inputParameters.channelCount = NUM_CHANNELS;
    inputParameters.sampleFormat = PA_SAMPLE_TYPE;
    inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency;
    inputParameters.hostApiSpecificStreamInfo = NULL;

    /* Record some audio. -------------------------------------------- */
    err = Pa_OpenStream(
              &stream,
              &inputParameters,
              NULL,                  /* &outputParameters, */
              SAMPLE_RATE,
              FRAMES_PER_BUFFER,
              paClipOff,      /* we won't output out of range samples so don't bother clipping them */
              NULL, /* no callback, use blocking API */
              NULL ); /* no callback, so no callback userData */
    if( err != paNoError ) goto error;

    err = Pa_StartStream( stream );
    if( err != paNoError ) goto error;
    printf("Now recording!!\n"); fflush(stdout);

    err = Pa_ReadStream( stream, recordedSamples, totalFrames );
    if( err != paNoError ) goto error;
    
    err = Pa_CloseStream( stream );
    if( err != paNoError ) goto error;

    /* Measure maximum peak amplitude. */
    max = 0;
    average = 0;
    for( i=0; i<numSamples; i++ )
    {
        val = recordedSamples[i];
        if( val < 0 ) val = -val; /* ABS */
        if( val > max )
        {
            max = val;
        }
        average += val;
    }

    average = average / numSamples;

    printf("Sample max amplitude = "PRINTF_S_FORMAT"\n", max );
    printf("Sample average = "PRINTF_S_FORMAT"\n", average );
/*  Was as below. Better choose at compile time because this
    keeps generating compiler-warnings:
    if( PA_SAMPLE_TYPE == paFloat32 )
    {
        printf("sample max amplitude = %f\n", max );
        printf("sample average = %f\n", average );
    }
    else
    {
        printf("sample max amplitude = %d\n", max );
        printf("sample average = %d\n", average );
    }
*/
    /* Write recorded data to a file. */
#if 0
    {
        FILE  *fid;
        fid = fopen("recorded.raw", "wb");
        if( fid == NULL )
        {
            printf("Could not open file.");
        }
        else
        {
            fwrite( recordedSamples, NUM_CHANNELS * sizeof(SAMPLE), totalFrames, fid );
            fclose( fid );
            printf("Wrote data to 'recorded.raw'\n");
        }
    }
#endif

    /* Playback recorded data.  -------------------------------------------- */
    
    outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
    if (outputParameters.device == paNoDevice) {
      fprintf(stderr,"Error: No default output device.\n");
      goto error;
    }
    outputParameters.channelCount = NUM_CHANNELS;
    outputParameters.sampleFormat =  PA_SAMPLE_TYPE;
    outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency;
    outputParameters.hostApiSpecificStreamInfo = NULL;

    printf("Begin playback.\n"); fflush(stdout);
    err = Pa_OpenStream(
              &stream,
              NULL, /* no input */
              &outputParameters,
              SAMPLE_RATE,
              FRAMES_PER_BUFFER,
              paClipOff,      /* we won't output out of range samples so don't bother clipping them */
              NULL, /* no callback, use blocking API */
              NULL ); /* no callback, so no callback userData */
    if( err != paNoError ) goto error;

    if( stream )
    {
        err = Pa_StartStream( stream );
        if( err != paNoError ) goto error;
        printf("Waiting for playback to finish.\n"); fflush(stdout);

        err = Pa_WriteStream( stream, recordedSamples, totalFrames );
        if( err != paNoError ) goto error;

        err = Pa_CloseStream( stream );
        if( err != paNoError ) goto error;
        printf("Done.\n"); fflush(stdout);
    }
    free( recordedSamples );

    Pa_Terminate();
    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;
}
示例#26
0
文件: dsd_audio.c 项目: argilo/gr-dsd
void
playSynthesizedVoice (dsd_opts * opts, dsd_state * state)
{
    ssize_t result;

    if (state->audio_out_idx > opts->delay)
    {
        // output synthesized speech to sound card
        if(opts->audio_out_type == 2)
        {
#ifdef USE_PORTAUDIO
            PaError err = paNoError;
            do
            {
                long available = Pa_GetStreamWriteAvailable( opts->audio_out_pa_stream );
                if(available < 0)
                    err = available;
                //printf("Frames available: %d\n", available);
                if( err != paNoError )
                    break;
                if(available > SAMPLE_RATE_OUT * PA_LATENCY_OUT)
                {
                    //It looks like this might not be needed for very small latencies. However, it's definitely needed for a bit larger ones.
                    //When PA_LATENCY_OUT == 0.500 I get output buffer underruns if I don't use this. With PA_LATENCY_OUT <= 0.100 I don't see those happen.
                    //But with PA_LATENCY_OUT < 0.100 I run the risk of choppy audio and stream errors.
                    printf("\nSyncing voice output stream\n");
                    err = Pa_StopStream( opts->audio_out_pa_stream );
                    if( err != paNoError )
                        break;
                }

                err = Pa_IsStreamActive( opts->audio_out_pa_stream );
                if(err == 0)
                {
                    printf("Start voice output stream\n");
                    err = Pa_StartStream( opts->audio_out_pa_stream );
                }
                else if(err == 1)
                {
                    err = paNoError;
                }
                if( err != paNoError )
                    break;

                //printf("write stream %d\n", state->audio_out_idx);
                err = Pa_WriteStream( opts->audio_out_pa_stream, (state->audio_out_buf_p - state->audio_out_idx), state->audio_out_idx );
                if( err != paNoError )
                    break;
            } while(0);

            if( err != paNoError )
            {
                fprintf( stderr, "An error occured while using the portaudio output stream\n" );
                fprintf( stderr, "Error number: %d\n", err );
                fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) );
            }

#endif
        }
        else if (opts->audio_out_fd == -1)
        {
            memcpy(state->output_buffer + state->output_offset, (state->audio_out_buf_p - state->audio_out_idx), (state->audio_out_idx * 2));
            state->output_offset += state->audio_out_idx;
        }
        else
        {
            result = write (opts->audio_out_fd, (state->audio_out_buf_p - state->audio_out_idx), (state->audio_out_idx * 2));
        }
        state->audio_out_idx = 0;
    }

    if (state->audio_out_idx2 >= 800000)
    {
        state->audio_out_float_buf_p = state->audio_out_float_buf + 100;
        state->audio_out_buf_p = state->audio_out_buf + 100;
        memset (state->audio_out_float_buf, 0, 100 * sizeof (float));
        memset (state->audio_out_buf, 0, 100 * sizeof (short));
        state->audio_out_idx2 = 0;
    }
}