Exemplo n.º 1
0
int AudioStreamManager::StreamAudio(ISoundDelegate* delegate)
{
	PaStreamParameters inputParameters, outputParameters;
	PaError err;

	soundDelegate = delegate;

	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 = 2;       /* stereo input */
	inputParameters.sampleFormat = PA_SAMPLE_TYPE;
	inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultLowInputLatency;
	inputParameters.hostApiSpecificStreamInfo = NULL;

	outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
	if (outputParameters.device == paNoDevice) {
		fprintf(stderr, "Error: No default output device.\n");
		goto error;
	}
	outputParameters.channelCount = 2;       /* stereo output */
	outputParameters.sampleFormat = PA_SAMPLE_TYPE;
	outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputParameters.device)->defaultLowOutputLatency;
	outputParameters.hostApiSpecificStreamInfo = NULL;
	
	err = Pa_OpenStream(
		&audioStream,
		&inputParameters,
		&outputParameters,
		SAMPLE_RATE,
		FRAMES_PER_BUFFER,
		0, /* paClipOff, */  /* we won't output out of range samples so don't bother clipping them */
		readStreamCallback,
		NULL);
	if (err != paNoError) goto error;

	delegate->willBeginPlay();

	err = Pa_StartStream(audioStream);
	if (err != paNoError) goto error;	
	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));
	delegate->didEndPlay();
	return -1;
}
Exemplo n.º 2
0
void GuitarSori::init( const int mFramesPerBuffer, const int mNumChannels, const int mSampleSize, PaSampleFormat mSampleFormat, const double mSampleRate)
{
	int numBytes, numBytesConverted;

	framesPerBuffer = mFramesPerBuffer;
	numChannels = mNumChannels;
	sampleSize = mSampleSize;
	sampleFormat = mSampleFormat;
	sampleRate = mSampleRate;

	numBytes = mFramesPerBuffer * mNumChannels * mSampleSize;
	numBytesConverted = mFramesPerBuffer * mNumChannels * 8;

	freeBuffers();
	sampleBlock = (char *)malloc(numBytes);
	sampleBlockConverted = (double *)malloc(numBytesConverted);
	sampleBlockFFT = (double *)malloc(numBytesConverted / 2);

	if ( !isBuffersReady() )
	{
		printf("Cannot allocate sample block\n");
		return;
	}

	memset(sampleBlock, 0x00, numBytes);
	memset(sampleBlockConverted, 0x00, numBytesConverted);
	memset(sampleBlockFFT, 0x00, numBytesConverted / 2);

	err = Pa_Initialize();

	printf("──────────────────────────────\n");
	inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */
	inputParameters.device = 1;
	printf("Input device # %d. : %s\n", inputParameters.device, Pa_GetDeviceInfo(inputParameters.device)->name);
	printf("Input LL: %g s\n", Pa_GetDeviceInfo(inputParameters.device)->defaultLowInputLatency);
	printf("Input HL: %g s\n", Pa_GetDeviceInfo(inputParameters.device)->defaultHighInputLatency);
	printf("Input HL: %g s\n", Pa_GetDeviceInfo(inputParameters.device)->defaultHighInputLatency);
	printf("Input Channel(MAX.) : %d ", Pa_GetDeviceInfo(inputParameters.device)->maxInputChannels);
	inputParameters.channelCount = numChannels;
	inputParameters.sampleFormat = sampleFormat;
	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 = numChannels;
	outputParameters.sampleFormat = sampleFormat;
	outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputParameters.device)->defaultHighOutputLatency;
	outputParameters.hostApiSpecificStreamInfo = NULL;

	err = Pa_OpenStream(&stream, &inputParameters, &outputParameters, sampleRate, framesPerBuffer, paClipOff, NULL, NULL);
	err = Pa_StartStream(stream);
}
Exemplo n.º 3
0
int main(void)
{
    PaStreamParameters outputParameters;
    PaStream *stream;
    PaError err;
    paTestData data;
    int i;
    printf("PortAudio Test: output sine wave.\n");

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

    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, /* As above. */
                         SAMPLE_RATE,
                         256,               /* Frames per buffer. */
                         paClipOff,         /* No out of range samples expected. */
                         patestCallback,
                         &data );
    if( err != paNoError ) goto error;

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

    printf("Hit ENTER to stop program.\n");
    getchar();

    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;
}
Exemplo n.º 4
0
static int init_media_processing(avdtp_media_codec_configuration_sbc_t configuration){
    int num_channels = configuration.num_channels;
    int sample_rate = configuration.sampling_frequency;
    
#ifdef DECODE_SBC
    btstack_sbc_decoder_init(&state, mode, handle_pcm_data, NULL);
#endif

#ifdef STORE_SBC_TO_WAV_FILE
    wav_writer_open(wav_filename, num_channels, sample_rate);  
#endif

#ifdef STORE_SBC_TO_SBC_FILE    
    sbc_file = fopen(sbc_filename, "wb"); 
#endif

#ifdef HAVE_PORTAUDIO
    // int frames_per_buffer = configuration.frames_per_buffer;
    PaError err;
    PaStreamParameters outputParameters;

    /* -- initialize PortAudio -- */
    err = Pa_Initialize();
    if (err != paNoError){
        printf("Error initializing portaudio: \"%s\"\n",  Pa_GetErrorText(err));
        return err;
    } 
    /* -- setup input and output -- */
    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,
           NULL,                /* &inputParameters */
           &outputParameters,
           sample_rate,
           0,
           paClipOff,           /* we won't output out of range samples so don't bother clipping them */
           patestCallback,      /* use callback */
           NULL );   
    
    if (err != paNoError){
        printf("Error initializing portaudio: \"%s\"\n",  Pa_GetErrorText(err));
        return err;
    }
    memset(ring_buffer_storage, 0, sizeof(ring_buffer_storage));
    btstack_ring_buffer_init(&ring_buffer, ring_buffer_storage, sizeof(ring_buffer_storage));
    pa_stream_started = 0;
#endif 
    media_initialized = 1;
    return 0;
}
Exemplo n.º 5
0
void handle_sound(adata_t *data)
{
  PaStream *stream;
  PaError error;
  PaStreamParameters outputParameters;

  /* initialize our data structure */
  data->position = 0;
  data->thread_idle = 0;
  data->sfInfo.format = SF_FORMAT_OGG;
  /* try to open the file */
  data->sndFile = sf_open(data->filepath, SFM_READ, &data->sfInfo);

  if (!data->sndFile)
  {
    printf("error opening file\n");
    exit(1);
  }

  /* start portaudio */
  Pa_Initialize();

  /* set the output parameters */
  outputParameters.device = Pa_GetDefaultOutputDevice(); /* use the default device */
  outputParameters.channelCount = data->sfInfo.channels; /* use the same number of channels as our sound file */
  outputParameters.sampleFormat = paInt32; /* 32bit int format */
  outputParameters.suggestedLatency = 0.2; /* 200 ms ought to satisfy even the worst sound card */
  outputParameters.hostApiSpecificStreamInfo = 0; /* no api specific data */

  /* try to open the output */
  error = Pa_OpenStream(&stream,  /* stream is a 'token' that we need to save for future portaudio calls */
                        0,  /* no input */
                        &outputParameters,
                        data->sfInfo.samplerate,  /* use the same sample rate as the sound file */
                        paFramesPerBufferUnspecified,  /* let portaudio choose the buffersize */
                        paNoFlag,  /* no special modes (clip off, dither off) */
                        Callback,  /* callback function defined above */
                        data ); /* pass in our data structure so the callback knows what's up */

  /* if we can't open it, then bail out */
  if (error)
  {
    printf("error opening output, error code = %i\n", error);
    Pa_Terminate();
  }

  /* when we start the stream, the callback starts getting called */
  Pa_StartStream(stream);
  long ms_length = ((double)data->sfInfo.frames / (double)data->sfInfo.samplerate) * 1000.;
  Pa_Sleep(ms_length); 
  Pa_CloseStream(stream); // stop the stream
  (*data).thread_complete = 1;
  Pa_Terminate(); // and shut down portaudio
}
Exemplo n.º 6
0
int main()
{
  SndData *data = (SndData *)malloc(sizeof(SndData));
  PaStream *stream;
  PaError error;
  PaStreamParameters outputParameters;

  /* initialize our data structure */
  data->position = 0;
  data->sfInfo.format = 0;
  /* try to open the file */
  data->sndFile = sf_open(FILE_NAME, SFM_READ, &data->sfInfo);

  if (!data->sndFile)
  {
    printf("error opening file\n");
    return 1;
  }

  /* start portaudio */
  Pa_Initialize();

  /* set the output parameters */
  outputParameters.device = Pa_GetDefaultOutputDevice(); /* use the default device */
  outputParameters.channelCount = data->sfInfo.channels; /* use the same number of channels as our sound file */
  outputParameters.sampleFormat = paInt32; /* 32bit int format */
  outputParameters.suggestedLatency = 0.01; /* 10 ms latency, if possible */
  outputParameters.hostApiSpecificStreamInfo = 0; /* no api specific data */

  /* try to open the output */
  error = Pa_OpenStream(&stream,  /* stream is a 'token' that we need to save for future portaudio calls */
                        0,  /* no input */
                        &outputParameters,
                        data->sfInfo.samplerate,  /* use the same sample rate as the sound file */
                        paFramesPerBufferUnspecified,  /* let portaudio choose the buffersize */
                        paNoFlag,  /* no special modes (clip off, dither off) */
                        Callback,  /* callback function defined above */
                        data ); /* pass in our data structure so the callback knows what's up */

  /* if we can't open it, then bail out */
  if (error) {
    printf("error opening output, error code = %i\n", error);
    Pa_Terminate();
    return 1;
  }

  /* when we start the stream, the callback starts getting called */
  Pa_StartStream(stream);
  Pa_Sleep(2000); /* pause for 2 seconds (2000ms) so we can hear a bit of the output */
  Pa_StopStream(stream); // stop the stream
  Pa_Terminate(); // and shut down portaudio
  return 0;
}
Exemplo n.º 7
0
int test(short interleaved)
{
    PaStream*           stream;
    PaStreamParameters  outputParameters;
    PaError             err;
    const PaDeviceInfo* pdi;
    paTestData          data;
    short               n;

    outputParameters.device = Pa_GetDefaultOutputDevice();  /* Default output device, max channels. */
    pdi = Pa_GetDeviceInfo(outputParameters.device);
    outputParameters.channelCount = pdi->maxOutputChannels;
    if (outputParameters.channelCount > MAX_CHANNELS)
        outputParameters.channelCount = MAX_CHANNELS;
    outputParameters.sampleFormat = paFloat32;              /* 32 bit floating point output */
    outputParameters.suggestedLatency = pdi->defaultLowOutputLatency;
    outputParameters.hostApiSpecificStreamInfo = NULL;
    
    data.interleaved = interleaved;
    data.numChannels = outputParameters.channelCount;
    for (n = 0; n < data.numChannels; n++)
        data.phases[n] = 0.0; /* Phases wrap and maybe don't need initialisation. */
    printf("%d ", data.numChannels);
    if (interleaved)
        printf("interleaved ");
    else
        {
        printf(" non-interleaved ");
        outputParameters.sampleFormat |= paNonInterleaved;
        }
    printf("channels.\n");

    err = Pa_OpenStream(&stream,
                        NULL,               /* No input. */
                        &outputParameters,
                        SAMPLE_RATE,        /* Sample rate. */
                        FRAMES_PER_BUFFER,  /* Frames per buffer. */
                        paClipOff,          /* Samples never out of range, no clipping. */
                        patestCallback,
                        &data);
    if (err == paNoError)
        {
        err = Pa_StartStream(stream);
        if (err == paNoError)
            {
            printf("Hit ENTER to stop this test.\n");
            getchar();
            err = Pa_StopStream(stream);
            }
        Pa_CloseStream( stream );
        }
    return err;    
}
Exemplo n.º 8
0
static int quisk_pa_name2index (struct sound_dev * dev, int is_capture)
{	// Based on the device name, set the portaudio index, or -1.
	// Return non-zero for error.  Not a portaudio device is not an error.
	const PaDeviceInfo * pInfo;
	int i, count;

	if (strncmp (dev->name, "portaudio", 9)) {
		dev->portaudio_index = -1;	// Name does not start with "portaudio"
		return 0;		// Not a portaudio device, not an error
	}
	if ( ! strcmp (dev->name, "portaudiodefault")) {
		if (is_capture)		// Fill in the default device index
			dev->portaudio_index = Pa_GetDefaultInputDevice();
		else
			dev->portaudio_index = Pa_GetDefaultOutputDevice();
		strncpy (dev->msg1, "Using default portaudio device", QUISK_SC_SIZE);
		return 0;
	}
	if ( ! strncmp (dev->name, "portaudio#", 10)) {		// Integer index follows "#"
		dev->portaudio_index = i = atoi(dev->name + 10);
		pInfo = Pa_GetDeviceInfo(i);
		if (pInfo) {
			snprintf (dev->msg1, QUISK_SC_SIZE, "PortAudio device %s",  pInfo->name);
			return 0;
		}
		else {
			snprintf (quisk_sound_state.err_msg, QUISK_SC_SIZE,
				"Can not find portaudio device number %s", dev->name + 10);
		}
		return 1;
	}
	if ( ! strncmp (dev->name, "portaudio:", 10)) {
		dev->portaudio_index = -1;
		count = Pa_GetDeviceCount();		// Search for string in device name
		for (i = 0; i < count; i++) {
			pInfo = Pa_GetDeviceInfo(i);
			if (pInfo && strstr(pInfo->name, dev->name + 10)) {
				dev->portaudio_index = i;
				snprintf (dev->msg1, QUISK_SC_SIZE, "PortAudio device %s",  pInfo->name);
				break;
			}
		}
		if (dev->portaudio_index == -1)	{	// Error
			snprintf (quisk_sound_state.err_msg, QUISK_SC_SIZE,
				"Can not find portaudio device named %s", dev->name + 10);
			return 1;
		}
		return 0;
	}
	snprintf (quisk_sound_state.err_msg, QUISK_SC_SIZE,
		"Did not recognize portaudio device %s", dev->name);
	return 1;
}
Exemplo n.º 9
0
static int pa_setsp(rsound *rsnd, PaStreamParameters *sp)
{
    sp->device = Pa_GetDefaultOutputDevice();
    if (sp->device == paNoDevice) {
        return -1;
    }
    sp->channelCount = 2; /* stereo output */
    sp->sampleFormat = paFloat32; /* 32bit floating point output */
    sp->suggestedLatency = Pa_GetDeviceInfo(sp->device)->defaultLowOutputLatency;

    return 0;
}
Exemplo n.º 10
0
bool PortAudio::open(long rate, int channels)
{

    if(mRate != rate || mChannels != channels) {
        close();
    }

    if(!isOpen) {
        //PaDeviceIndex default_device = 2;
        PaDeviceIndex default_device = Pa_GetDefaultOutputDevice();
        if( default_device == paNoDevice ) {
            LOG4CXX_ERROR(narratorPaLog, "Pa_GetDefaultOutputDevice failed, however, device count is: " << Pa_GetDeviceCount() );
            return false;
        }

        mOutputParameters.device = default_device; /* default output device */
        mOutputParameters.channelCount = channels;
        mOutputParameters.sampleFormat = paFloat32;
        mOutputParameters.suggestedLatency = Pa_GetDeviceInfo( mOutputParameters.device )->defaultHighOutputLatency;
        mOutputParameters.hostApiSpecificStreamInfo = NULL;

        const PaDeviceInfo* devinfo = Pa_GetDeviceInfo(mOutputParameters.device);
        const PaHostApiInfo* hostapiinfo = Pa_GetHostApiInfo(devinfo->hostApi);

        LOG4CXX_DEBUG(narratorPaLog, "Opening device: " << devinfo->name << " (" << hostapiinfo->name << "), channels: " << channels << ", rate: " << rate <<" (" << devinfo->defaultSampleRate << ")");

        unsigned long framesPerBuffer = 1024;

#ifdef WIN32
        framesPerBuffer = 4096;
#endif

        mError = Pa_OpenStream(&pStream, NULL, &mOutputParameters, rate, framesPerBuffer/*paFramesPerBufferUnspecified*/,
                paNoFlag, pa_stream_callback, this);

        if(mError != paNoError) {
            LOG4CXX_ERROR(narratorPaLog, "Failed to open stream: " << Pa_GetErrorText(mError));
            return false;
        }

        mRate = rate;
        mChannels = channels;
        isOpen = true;
        isStarted = false;

        mError = Pa_SetStreamFinishedCallback(pStream, pa_stream_finished_callback);
        if(mError != paNoError) {
            LOG4CXX_ERROR(narratorPaLog, "Failed to set FinishedCallback: " << Pa_GetErrorText(mError));
        }

    }
    return true;
}
Exemplo n.º 11
0
PaError TestOnce( int buffersize, PaDeviceIndex device )
{
    PaStreamParameters outputParameters;
    PaStream *stream;
    PaError err;
    paTestData data;
    int i;
    int totalSamps;
    /* initialise sinusoidal wavetable */
    for( i=0; i<TABLE_SIZE; i++ )
    {
        data.sine[i] = (short) (32767.0 * sin( ((double)i/(double)TABLE_SIZE) * M_PI * 2. ));
    }
    data.left_phase = data.right_phase = 0;
    data.sampsToGo = totalSamps =  NUM_SECONDS * SAMPLE_RATE; /* Play for a few seconds. */
    err = Pa_Initialize();
    if( err != paNoError ) goto error;
    
    if( device == -1 )
        outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
    else
        outputParameters.device = device ;
    outputParameters.channelCount = 2;                      /* stereo output */
    outputParameters.sampleFormat = paInt16;                /* 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,
              buffersize,                   /* frames per buffer */
              (paClipOff | paDitherOff),
              patest1Callback,
              &data );
    if( err != paNoError ) goto error;

    err = Pa_StartStream( stream );
    if( err != paNoError ) goto error;
    printf("Waiting for sound to finish.\n");
    Pa_Sleep(1000*NUM_SECONDS);
    err = Pa_CloseStream( stream );
    if( err != paNoError ) goto error;
    Pa_Terminate();
    return paNoError;
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 ) );
    fprintf( stderr, "Host Error message: %s\n", Pa_GetLastHostErrorInfo()->errorText );
    return err;
}
Exemplo n.º 12
0
int main(void)
{
    PaStream *stream;
    PaStreamParameters outputParameters;
    PaError err;
    paTestData data;
    int totalSamps;

    printf("PortAudio Test: output " FORMAT_NAME "\n");

    data.left_phase = data.right_phase = 0.0;
    data.framesToGo = totalSamps =  NUM_SECONDS * SAMPLE_RATE; /* Play for a few seconds. */
    err = Pa_Initialize();
    if( err != paNoError ) goto error;


    outputParameters.device           = Pa_GetDefaultOutputDevice(); /* Default output device. */
    outputParameters.channelCount     = 2;                           /* Stereo output */
    outputParameters.sampleFormat     = TEST_FORMAT;                 /* Selected above. */
    outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputParameters.device)->defaultLowOutputLatency;
    outputParameters.hostApiSpecificStreamInfo = NULL;
    err = Pa_OpenStream( &stream,
                         NULL,                  /* No input. */
                         &outputParameters,     /* As above. */
                         SAMPLE_RATE,
                         FRAMES_PER_BUFFER,
                         paClipOff,      /* we won't output out of range samples so don't bother clipping them */
                         patestCallback,
                         &data );
    if( err != paNoError ) goto error;

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

    printf("Waiting %d seconds for sound to finish.\n", NUM_SECONDS );

    while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) Pa_Sleep(100);
    if( err < 0 ) goto error;

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

    printf("PortAudio Test Finished: " FORMAT_NAME "\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;
}
Exemplo n.º 13
0
Arquivo: jeg.c Projeto: Claudiu/jeg
int main( int argc, const char ** argv )
{
    PaStreamParameters outputParameters;
    PaError pa_err;
    SF_INFO sfinfo;

    int i;
    for (i = 1; i < argc; i++)
    {
        if (!strncmp(argv[i], "-m", 2))
        {
            mute = 1;
        }
        if (!strncmp(argv[i], "-o", 2))
        {
            to_stdout = 1;
        }
    }

    gen_default_drums();

    pa_err = Pa_Initialize();
    outputParameters.device = Pa_GetDefaultOutputDevice();
    outputParameters.channelCount = CHANNELS;
    outputParameters.sampleFormat = paFloat32;
    outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency;
    outputParameters.hostApiSpecificStreamInfo = NULL;
    pa_err = Pa_OpenStream( &stream, NULL, &outputParameters, SAMPLE_RATE, BUFFER_SIZE, paClipOff, audio_callback, NULL );

    sfinfo.samplerate = SAMPLE_RATE;
    sfinfo.channels = CHANNELS;
    sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_FLOAT;
    wave_output = sf_open( OUTPUT_FILE, SFM_WRITE, &sfinfo );

    convert_buf = (int32_t*)malloc(SAMPLE_RATE * 4 * 2);

    srand( time( 0 ) );

    bass_z = 0.0f;
    bass_freq = midi_to_hz( BASE_NOTE );

    pa_err = Pa_StartStream( stream );

    while( 1 )
        Pa_Sleep( 10000 );

    sf_close( wave_output );
    pa_err = Pa_StopStream( stream );
    pa_err = Pa_CloseStream( stream );
    Pa_Terminate();

    return 0;
}
Exemplo n.º 14
0
int main(void)
{
    PaStream *stream;
    PaError err;
    paTestData data;
    int i;
    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++ )
    {
        data.sine[i] = (float) sin( ((double)i/(double)TABLE_SIZE) * M_PI * 2. );
    }
    data.left_phase = data.right_phase = 0;
    err = Pa_Initialize();
    if( err != paNoError ) goto error;
    err = Pa_OpenStream(
              &stream,
              paNoDevice,/* default input device */
              0,              /* no input */
              paFloat32,  /* 32 bit floating point input */
              0, /* default latency */
              NULL,
              Pa_GetDefaultOutputDevice(), /* default output device */
              2,          /* stereo output */
              paFloat32,      /* 32 bit floating point output */
              0, /* default latency */
              NULL,
              SAMPLE_RATE,
              FRAMES_PER_BUFFER,
              paClipOff,      /* we won't output out of range samples so don't bother clipping them */
              patestCallback,
              &data );
    if( err != paNoError ) goto error;
    err = Pa_StartStream( stream );
    if( err != paNoError ) goto error;
    printf("Play for %d seconds.\n", NUM_SECONDS );
    Pa_Sleep( NUM_SECONDS * 1000 );

    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;
}
Exemplo n.º 15
0
PaDeviceIndex SoundcardDialog::getOutputSource()
{
    int index = ui->outputComboBox->currentIndex();
    if (index == -1)
    {
        // no item was selected, so we return the
        // default input device
        return Pa_GetDefaultOutputDevice();
    }
    else
    {
        bool ok;
        PaDeviceIndex idx = ui->outputComboBox->itemData(index).toInt(&ok);
        if (!ok)
        {
            // conversion to int not succesfull
            // return the default input device .. :(
            return Pa_GetDefaultOutputDevice();
        }
        return idx;
    }
}
Exemplo n.º 16
0
/** 
 * Initializes the output parameters for playback
 *
 * Function will initailize all the members of the passed
 * in PaStreamParameters struct.
 * @param out_pars a pointer to a PaStreamParameters struct. 
 * @param format the sample format for the output device to use
 */
void setupDefaultOutputParameters( PaStreamParameters *out_pars,
									PaSampleFormat format)
{
    out_pars->device = Pa_GetDefaultOutputDevice();
    if (out_pars->device == paNoDevice)
        fatal_terminate("No default output device");
    out_pars->channelCount = 
			Pa_GetDeviceInfo(out_pars->device)-> maxOutputChannels;
    out_pars->sampleFormat = format;
    out_pars->suggestedLatency = 
        Pa_GetDeviceInfo(out_pars->device)->defaultLowOutputLatency;
    out_pars->hostApiSpecificStreamInfo = NULL;
}
Exemplo n.º 17
0
LVAL prepare_audio(LVAL play, SF_INFO *sf_info, PaStream **audio_stream)
{
    PaStreamParameters output_parameters;
    int i;
    int num_devices;
    const PaDeviceInfo *device_info;
    const PaHostApiInfo *host_info;

    if (!portaudio_initialized) {
        if (portaudio_error(Pa_Initialize(), 
                            "could not initialize portaudio")) {
            return NIL;
        }
        portaudio_initialized = TRUE;
    }
        
    output_parameters.device = Pa_GetDefaultOutputDevice(); 
    output_parameters.channelCount = sf_info->channels;
    output_parameters.sampleFormat = paFloat32;
    output_parameters.hostApiSpecificStreamInfo = NULL;
    /* remember that Nyquist has to do GC */
    output_parameters.suggestedLatency = sound_latency;

    // Initialize the audio stream for output
    // If this is Linux, prefer to open ALSA device
    num_devices = Pa_GetDeviceCount();
    for (i = 0; i < num_devices; i++) {
        device_info = Pa_GetDeviceInfo(i);
        host_info = Pa_GetHostApiInfo(device_info->hostApi);
        if (host_info->type == paALSA) {
            output_parameters.device = i;
            break;
        }
    }

    if (portaudio_error(
         Pa_OpenStream(audio_stream, NULL /* input */, &output_parameters,
                   sf_info->samplerate, max_sample_block_len, 
                   paClipOff, NULL /* callback */, NULL /* userdata */),
         "could not open audio")) {
        return NIL;
    }
    flush_count = (long) (sf_info->samplerate * (sound_latency + 0.2));

    if (portaudio_error(Pa_StartStream(*audio_stream), 
                        "could not start audio")) {
        return NIL;
    }

    return play;
}
Exemplo n.º 18
0
// play a module using portaudio.
void play(DUH *duh) {
	// init portaudio, redirecting stderr output temporarily; a lot of junk
	// gets printed otherwise. this won't work on windows, but who cares?
	int old_stderr = dup(2);
	int new_stderr = open("/dev/null", O_WRONLY);
	dup2(new_stderr, 2);
	PaError err = Pa_Initialize();
	close(new_stderr);
	dup2(old_stderr, 2);
	close(old_stderr);
	if (err != paNoError)
		die("could not init PortAudio: %s\n", Pa_GetErrorText(err));
	atexit(&pa_terminate);

	// get default device info
	PaDeviceIndex index = Pa_GetDefaultOutputDevice();
	if (index == paNoDevice)
		die("could not get default output device\n");
	callback_data cd;
	const PaDeviceInfo *dev = Pa_GetDeviceInfo(index);
	cd.sample_rate = dev->defaultSampleRate;
	cd.delta = 65536.0f / cd.sample_rate;

	// open and start output stream
	PaStream *stream;
	cd.sr = duh_start_sigrenderer(duh, 0, channels, 0);
	err = Pa_OpenDefaultStream(&stream, 0, channels, paInt16,
			dev->defaultSampleRate, paFramesPerBufferUnspecified,
			callback, &cd);
	if (err != paNoError) {
		duh_end_sigrenderer(cd.sr);
		unload_duh(duh);
		die("could not open default stream: %s\n",
				Pa_GetErrorText(err));
	}
	if ((err = Pa_StartStream(stream)) != paNoError) {
		duh_end_sigrenderer(cd.sr);
		unload_duh(duh);
		die("could not start stream: %s\n", Pa_GetErrorText(err));
	}

	init_sigrenderer(cd.sr);

	// play
	while (Pa_IsStreamActive(stream) == 1)
		Pa_Sleep(100);

	// clean up
	Pa_CloseStream(stream);
	duh_end_sigrenderer(cd.sr);
}
Exemplo n.º 19
0
static PaError DoTest( int flags )
{
    PaStream *stream;
    PaError    err = paNoError;
    paTestData data;
    PaStreamParameters outputParameters;

    InitializeTestData( &data );       

    outputParameters.device = Pa_GetDefaultOutputDevice();
    if (outputParameters.device == paNoDevice) {
      fprintf(stderr,"Error: No default output device.\n");
      goto error;
    }
    outputParameters.channelCount = 2;
    outputParameters.hostApiSpecificStreamInfo = NULL;
    outputParameters.sampleFormat = paFloat32;
    outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency;

    /* Open an audio I/O stream. */
    err = Pa_OpenStream(
        &stream,
        NULL,                         /* no input */
        &outputParameters,
        SAMPLE_RATE,
        FRAMES_PER_BUFFER,            /* frames per buffer */
        paClipOff | flags,      /* we won't output out of range samples so don't bother clipping them */
        patestCallback,
        &data );
    if( err != paNoError ) goto error;


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

    printf("hear \"BEEP\"\n" );
    fflush(stdout);

    while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) Pa_Sleep(SLEEP_MSEC);
    if( err < 0 ) goto error;

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

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

    return err;
error:
    return err;
}
Exemplo n.º 20
0
void PortAudioHelper::loadDevices() {
    DEVICE_COUNT = Pa_GetDeviceCount();
    DEFAULT_INPUT_DEVICE = Pa_GetDefaultInputDevice();
    DEFAULT_OUTPUT_DEVICE = Pa_GetDefaultOutputDevice();
    for (PaDeviceIndex i=0; i<DEVICE_COUNT; i++) {
        AudioDeviceInfo deviceInfo;
        deviceInfo.deviceInfo = *Pa_GetDeviceInfo(i);
        deviceInfo.supportedSampleRates = getSupportedSampleRate(i);
        DEVICES.append(deviceInfo);
    }

    CURRENT_INPUT_DEVICE = loadFromSettings(keyDefaultInputDevice, DEFAULT_INPUT_DEVICE).toInt();
    CURRENT_OUTPUT_DEVICE = loadFromSettings(keyDefaultOutputDevice, DEFAULT_OUTPUT_DEVICE).toInt();
}
Exemplo n.º 21
0
int SoundIO::init_sound(int achannels)
{
    this->channels = achannels;

    PaStreamParameters outputParameters;
    PaError err;

    // initialize audio
    err = Pa_Initialize();
    if( err != paNoError ) return 1;

    std::cout << "Initialized Portaudio." << std::endl;

    outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */

    outputParameters.channelCount = channels;
    outputParameters.sampleFormat = paFloat32;
    outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency;
    outputParameters.hostApiSpecificStreamInfo = nullptr;

    err = Pa_OpenStream(
              &stream,
              nullptr, /* no input */
              &outputParameters,
              Fs,
              FRAMES_PER_BUFFER,
              paClipOff,
              nullptr,
              nullptr );
    if( err != paNoError ) return 1;

    err = Pa_StartStream( stream );
    if( err != paNoError ) return 1;
    std::cout << "Stream Opened" << std::endl;


    //////////////////////////

    SF_INFO sfinfo;
    sfinfo.channels = channels;
    sfinfo.samplerate = Fs;
    //sfinfo.format = SF_FORMAT_OGG | SF_FORMAT_VORBIS;
    sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_FLOAT;

    file = sf_open("sound.wav", SFM_WRITE, &sfinfo);

    std::cout << "File Opened" << std::endl;

    return 0;
}
Exemplo n.º 22
0
static PaDeviceIndex FindOutputOnlyDevice(void)
{
    PaDeviceIndex result = Pa_GetDefaultOutputDevice();
    if( result != paNoDevice && Pa_GetDeviceInfo(result)->maxInputChannels == 0 )
        return result;

    for( result = 0; result < Pa_GetDeviceCount(); ++result )
    {
        if( Pa_GetDeviceInfo(result)->maxInputChannels == 0 )
            return result;
    }

    return paNoDevice;
}
Exemplo n.º 23
0
void *play(void *repeat_ptr) {
  int n;
  int *repeat = (int *)repeat_ptr;
  PaStreamParameters out_param;
  PaStream * stream;
  PaError err;
  SNDFILE * file;
  SF_INFO sfinfo;

  struct timespec tim, tim2;
  tim.tv_sec  = 0;
  tim.tv_nsec = 500000000L;

  for (n=0; n<(*repeat); ++n) {
    file = sf_open("whistle.wav", SFM_READ, &sfinfo);
    printf("%d frames %d samplerate %d channels\n", (int)sfinfo.frames, sfinfo.samplerate, sfinfo.channels);

    /* init portaudio */
    err = Pa_Initialize();
    error_check(err);

    /* we are using the default device */
    out_param.device = Pa_GetDefaultOutputDevice();
    if (out_param.device == paNoDevice)
        fprintf(stderr, "Haven't found an audio device!\n");

    /* stero or mono */
    out_param.channelCount = sfinfo.channels;
    out_param.sampleFormat = paInt16;
    out_param.suggestedLatency = Pa_GetDeviceInfo(out_param.device)->defaultLowOutputLatency;
    out_param.hostApiSpecificStreamInfo = NULL;

    err = Pa_OpenStream(&stream, NULL, &out_param, sfinfo.samplerate, paFramesPerBufferUnspecified, paClipOff, output_cb, file);
    error_check(err);

    err = Pa_StartStream(stream);
    error_check(err);

    Pa_Sleep(800);

    err = Pa_StopStream(stream);
    error_check(err);
    err = Pa_CloseStream(stream);
    error_check(err);
    Pa_Terminate();
    sf_close(file);
    nanosleep(&tim, &tim2);
  }
  is_playing=0;
}
Exemplo n.º 24
0
int main(int argc, char ** argv) {

	struct sigaction s;
	sigset_t ss;
	sigemptyset(&ss);
	s.sa_handler = &on_interrupt;
	sigemptyset(&s.sa_mask);
	s.sa_flags = 0;
	s.sa_restorer = NULL;
	sigaction(SIGINT, &s, NULL);

	PaDeviceIndex odev;
	PaDeviceInfo * odev_info;
	PaStreamParameters odev_p;
	PaStream * ostream;

	int bufsz = FRAMES_PER_BUFFER * CHANNELS * SAMPLE_SIZE;
	int bufrd = 0;
	int i;
	char * buf = (char*) malloc(bufsz);
	
	Pa_Initialize();
	odev = Pa_GetDefaultOutputDevice();
	odev_info = Pa_GetDeviceInfo(odev);
	
	odev_p.device = odev;
	odev_p.channelCount = CHANNELS;
	odev_p.sampleFormat = SAMPLE_TYPE;
	odev_p.suggestedLatency = odev_info->defaultLowOutputLatency;
	odev_p.hostApiSpecificStreamInfo = NULL;
	
	i = Pa_OpenStream(&ostream, NULL, &odev_p, SAMPLE_RATE, FRAMES_PER_BUFFER,
	             paNoFlag, NULL, NULL);
	//printf("s = %d\n",i);
	Pa_StartStream(ostream);
	fd = open(argv[1], O_RDONLY);
	
	for (;;) {
		bufrd = 0;
		while (bufrd < bufsz) {
			i = read(fd, buf+bufrd, bufsz-bufrd);
			//printf("read %d\n", i);
			bufrd += i;
			if (i == 0)
				shutdown(1);
		}
		Pa_WriteStream(ostream, buf, FRAMES_PER_BUFFER);
	}
}
Exemplo n.º 25
0
    void init() {
        PaError error;
        PaStreamParameters outputParameters;
        /* initialize our data structure */
        this->positionFrame = 0;
        this->sfInfo.format = 0;
        /* try to open the file */
        this->sndFile = sf_open(filename.c_str(), SFM_READ, &this->sfInfo);

        if (!this->sndFile) {
            printf("error opening file\n");
            return;
        }

        duration = sfInfo.frames / sfInfo.samplerate;


        /* start portaudio */
        Pa_Initialize();
        /* set the output parameters */
        /* use the default device */
        outputParameters.device = Pa_GetDefaultOutputDevice();
        /* use the same number of channels as our sound file */
        outputParameters.channelCount = this->sfInfo.channels;
//        sfInfo.format
        /* 32bit int format */
        outputParameters.sampleFormat = paInt32;
        /* 200 ms ought to satisfy even the worst sound card */
        outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputParameters.device)->defaultHighOutputLatency;
        outputParameters.hostApiSpecificStreamInfo = 0; /* no api specific data */

        /* try to open the output */
        error = Pa_OpenStream(&stream,  /* stream is a 'token' that we need to save for future portaudio calls */
                              0,  /* no input */
                              &outputParameters,
                              sfInfo.samplerate,  /* use the same sample rate as the sound file */
                              paFramesPerBufferUnspecified,  /* let portaudio choose the buffersize */
                              paNoFlag,  /* no special modes (clip off, dither off) */
                              _paCallBack,  /* callback function defined above */
                              this); /* pass in our data structure so the callback knows what's up */

        /* if we can't open it, then bail out */
        if (error) {
            printf("error opening output, error code = %i\n", error);
            Pa_Terminate();
            return;
        }
        _isInit = true;
    }
Exemplo n.º 26
0
PaError PlaySine( paTestData *data, PaStreamFlags flags, float amplitude )
{
    PaStream*           stream;
    PaStreamParameters  outputParameters;
    PaError             err;

    data->left_phase = data->right_phase = 0;
    data->amplitude  = amplitude;

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

    outputParameters.device = Pa_GetDefaultOutputDevice();  /* default output device */
    if (outputParameters.device == paNoDevice) {
      fprintf(stderr,"Error: No default output device.\n");
      goto done;
    }
    outputParameters.channelCount = 2;                      /* stereo output */
    outputParameters.hostApiSpecificStreamInfo = NULL;
    outputParameters.sampleFormat = paFloat32;      /* 32 bit floating point output. */
                                                    /* When you change this, also    */
                                                    /* adapt the callback routine!   */ 
    outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )
                                        ->defaultLowOutputLatency;   /* Low latency. */
    err = Pa_OpenStream( &stream,
                         NULL,                              /* No input. */
                         &outputParameters,
                         SAMPLE_RATE,
                         1024,                              /* frames per buffer */
                         flags,
                         sineCallback,
                         (void*)data );
    if (err != paNoError)
        goto done;

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

    Pa_Sleep( NUM_SECONDS * 1000 );
    printf("CPULoad = %8.6f\n", Pa_GetStreamCpuLoad(stream));
    
    err = Pa_CloseStream( stream );
done:
    Pa_Sleep( 250 );  /* Just a small silence. */
    Pa_Terminate();
    return err;
}
Exemplo n.º 27
0
bool			PAudioStream::initOutput()
{
  if (_buffer->output == NULL)
    return (false);
  if ((_outputParam.device = Pa_GetDefaultOutputDevice()) == paNoDevice)
    {
      qDebug() << "No default output device.";
      return (false);
    }
  _outputParam.channelCount = NUM_CHANNELS;
  _outputParam.sampleFormat = PA_SAMPLE_TYPE;
  _outputParam.suggestedLatency = (Pa_GetDeviceInfo(_outputParam.device))->defaultLowOutputLatency;
  _outputParam.hostApiSpecificStreamInfo = NULL;
  return (true);
}
Exemplo n.º 28
0
QString DevicePortAudio::deviceOutputDefaultName()
{
	PaDeviceIndex		 DevIdx = Pa_GetDefaultOutputDevice();

	if( DevIdx == paNoDevice )
	{
		return( QString() );
	}

	const PaDeviceInfo	*DevInf = Pa_GetDeviceInfo( DevIdx );

	const PaHostApiInfo *HstInf = Pa_GetHostApiInfo( DevInf->hostApi );

	return( QString( "%1: %2" ).arg( HstInf->name ).arg( DevInf->name ) );
}
Exemplo n.º 29
0
void		AudioManager::initOutput()
{
    if ((this->_outputParam.device = Pa_GetDefaultOutputDevice()) == paNoDevice)
    {
        this->errorAudio();
        return ;
    }
	this->_outputParam.channelCount = 1;
	this->_outputParam.sampleFormat = PA_SAMPLE_TYPE;
	this->_outputParam.suggestedLatency = Pa_GetDeviceInfo(this->_outputParam.device)->defaultHighOutputLatency;
	this->_outputParam.hostApiSpecificStreamInfo = NULL;
//	std::cout << "Output device # " << this->_outputParam.device << std::endl;
//	std::cout << "Output LowLatency : " << Pa_GetDeviceInfo(this->_outputParam.device)->defaultLowOutputLatency << std::endl;
//	std::cout << "Output HighLatency : " << Pa_GetDeviceInfo(this->_outputParam.device)->defaultHighOutputLatency << std::endl;
}
Exemplo n.º 30
0
	CPAManager::CPAManager(CRefPtr<Audio::IDriver> pDriver) :
		m_pDriver(pDriver),
		m_uDefaultIndex(0)
	{
		Log::Write(L"Initializing PortAudio Audio manager...");

		auto uError = Pa_Initialize();
		if(uError != paNoError){
			CR_THROW(L"Failed to initialize port audio, Error: " + Utils::ToErrorString(uError));
		}

		Log::Write(L"Enumerating audio adapters...", Log::LogLevel::Debug);
		auto uDeviceCount = Pa_GetDeviceCount();
		for(PaDeviceIndex uIndex = 0; uIndex < uDeviceCount; uIndex++){
			auto pInfo = Pa_GetDeviceInfo(uIndex);
			auto pApiInfo = Pa_GetHostApiInfo(pInfo->hostApi);
			
			auto strAdapter = String::FromANSI(reinterpret_cast<const int8*>(pInfo->name));
			auto strHostApi = String::FromANSI(reinterpret_cast<const int8*>(pApiInfo->name));

			strAdapter += L"[" + strHostApi + L"]";

			Log::Write(L"Audio Adapter Found: " + strAdapter, Log::LogLevel::Debug);
			this->m_strAdapterList.Add(strAdapter);
		}
		Log::Write(L"End of enumeration of audio adapters.", Log::LogLevel::Debug);

		if(!this->m_strAdapterList.IsEmpty()){
			Log::Write(L"Finding default audio adapter...", Log::LogLevel::Debug);

			auto uDefaultIndex = Pa_GetDefaultOutputDevice();
			if(uDefaultIndex == paNoDevice){
				Log::Write(L"Got null pointer for default device - assuming default as first in list.");
				uDefaultIndex = 0;
			}

			auto pInfo = Pa_GetDeviceInfo(uDefaultIndex);
			auto pApiInfo = Pa_GetHostApiInfo(pInfo->hostApi);
			
			auto strAdapter = String::FromANSI(reinterpret_cast<const int8*>(pInfo->name));
			auto strHostApi = String::FromANSI(reinterpret_cast<const int8*>(pApiInfo->name));

			strAdapter += L"[" + strHostApi + L"]";
			Log::Write(L"Found default PortAudio adapter: " + strAdapter, Log::LogLevel::Debug);

			this->m_uDefaultIndex = uDefaultIndex;
		}
	}