コード例 #1
0
ファイル: AudioPortAudio.cpp プロジェクト: BaraMGB/lmms
AudioPortAudio::AudioPortAudio( bool & _success_ful, Mixer * _mixer ) :
	AudioDevice( tLimit<ch_cnt_t>(
		ConfigManager::inst()->value( "audioportaudio", "channels" ).toInt(),
					DEFAULT_CHANNELS, SURROUND_CHANNELS ),
								_mixer ),
	m_paStream( NULL ),
	m_wasPAInitError( false ),
	m_outBuf( new surroundSampleFrame[mixer()->framesPerPeriod()] ),
	m_outBufPos( 0 ),
	m_stopSemaphore( 1 )
{
	_success_ful = false;

	m_outBufSize = mixer()->framesPerPeriod();

	PaError err = Pa_Initialize();
	
	if( err != paNoError ) {
		printf( "Couldn't initialize PortAudio: %s\n", Pa_GetErrorText( err ) );
		m_wasPAInitError = true;
		return;
	}

	if( Pa_GetDeviceCount() <= 0 )
	{
		return;
	}
	
	const QString& backend = ConfigManager::inst()->value( "audioportaudio", "backend" );
	const QString& device = ConfigManager::inst()->value( "audioportaudio", "device" );
		
	PaDeviceIndex inDevIdx = -1;
	PaDeviceIndex outDevIdx = -1;
	const PaDeviceInfo * di;
	for( int i = 0; i < Pa_GetDeviceCount(); ++i )
	{
		di = Pa_GetDeviceInfo( i );
		if( di->name == device &&
			Pa_GetHostApiInfo( di->hostApi )->name == backend )
		{
			inDevIdx = i;
			outDevIdx = i;
		}
	}

	if( inDevIdx < 0 )
	{
		inDevIdx = Pa_GetDefaultInputDevice();
	}
	
	if( outDevIdx < 0 )
	{
		outDevIdx = Pa_GetDefaultOutputDevice();
	}

	if( inDevIdx < 0 || outDevIdx < 0 )
	{
		return;
	}

	double inLatency = 0;//(double)mixer()->framesPerPeriod() / (double)sampleRate();
	double outLatency = 0;//(double)mixer()->framesPerPeriod() / (double)sampleRate();

	//inLatency = Pa_GetDeviceInfo( inDevIdx )->defaultLowInputLatency;
	//outLatency = Pa_GetDeviceInfo( outDevIdx )->defaultLowOutputLatency;
	const int samples = mixer()->framesPerPeriod();
	
	// Configure output parameters.
	m_outputParameters.device = outDevIdx;
	m_outputParameters.channelCount = channels();
	m_outputParameters.sampleFormat = paFloat32; // 32 bit floating point output
	m_outputParameters.suggestedLatency = outLatency;
	m_outputParameters.hostApiSpecificStreamInfo = NULL;
	
	// Configure input parameters.
	m_inputParameters.device = inDevIdx;
	m_inputParameters.channelCount = DEFAULT_CHANNELS;
	m_inputParameters.sampleFormat = paFloat32; // 32 bit floating point input
	m_inputParameters.suggestedLatency = inLatency;
	m_inputParameters.hostApiSpecificStreamInfo = NULL;
	
	// Open an audio I/O stream. 
	err = Pa_OpenStream(
			&m_paStream,
			supportsCapture() ? &m_inputParameters : NULL,	// The input parameter
			&m_outputParameters,	// The outputparameter
			sampleRate(),
			samples,
			paNoFlag,		// Don't use any flags
			_process_callback, 	// our callback function
			this );

	if( err == paInvalidDevice && sampleRate() < 48000 )
	{
		printf("Pa_OpenStream() failed with 44,1 KHz, trying again with 48 KHz\n");
		// some backends or drivers do not allow 32 bit floating point data
		// with a samplerate of 44100 Hz
		setSampleRate( 48000 );
		err = Pa_OpenStream(
				&m_paStream,
				supportsCapture() ? &m_inputParameters : NULL,	// The input parameter
				&m_outputParameters,	// The outputparameter
				sampleRate(),
				samples,
				paNoFlag,		// Don't use any flags
				_process_callback, 	// our callback function
				this );
	}

	if( err != paNoError )
	{
		printf( "Couldn't open PortAudio: %s\n", Pa_GetErrorText( err ) );
		return;
	}

	printf( "Input device: '%s' backend: '%s'\n", Pa_GetDeviceInfo( inDevIdx )->name, Pa_GetHostApiInfo( Pa_GetDeviceInfo( inDevIdx )->hostApi )->name );
	printf( "Output device: '%s' backend: '%s'\n", Pa_GetDeviceInfo( outDevIdx )->name, Pa_GetHostApiInfo( Pa_GetDeviceInfo( outDevIdx )->hostApi )->name );

	m_stopSemaphore.acquire();

	// TODO: debug Mixer::pushInputFrames()
	//m_supportsCapture = true;

	_success_ful = true;
}
コード例 #2
0
ファイル: paex_wmme_ac3.c プロジェクト: Ashura-X/mame
int main(int argc, char* argv[])
{
    PaStreamParameters outputParameters;
    PaWinMmeStreamInfo wmmeStreamInfo;
    PaStream *stream;
    PaError err;
    paTestData data;
    int deviceIndex;
    FILE *fp;
    const char *fileName = "c:\\test_48k.ac3.spdif";
    data.buffer = NULL;

    printf("usage: patest_wmme_ac3 fileName [paDeviceIndex]\n");
    printf("**IMPORTANT*** The provided file must include the spdif preamble at the start of every AC-3 frame. Using a normal ac3 file won't work.\n");
    printf("PortAudio Test: output a raw spdif ac3 stream. SR = %d, BufSize = %d, Chans = %d\n", 
            SAMPLE_RATE, FRAMES_PER_BUFFER, CHANNEL_COUNT);

        
    if( argc >= 2 )
        fileName = argv[1];

    printf( "reading spdif ac3 raw stream file %s\n", fileName );

    fp = fopen( fileName, "rb" );
    if( !fp ){
        fprintf( stderr, "error opening spdif ac3 file.\n" );
        return -1;
    }
    /* get file size */
    fseek( fp, 0, SEEK_END );
    data.bufferSampleCount = ftell( fp ) / sizeof(short);
    fseek( fp, 0, SEEK_SET );

    /* allocate buffer, read the whole file into memory */
    data.buffer = (short*)malloc( data.bufferSampleCount * sizeof(short) );
    if( !data.buffer ){
        fprintf( stderr, "error allocating buffer.\n" );
        return -1;
    }

    fread( data.buffer, sizeof(short), data.bufferSampleCount, fp );
    fclose( fp );

    data.playbackIndex = 0;

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

	deviceIndex = Pa_GetHostApiInfo( Pa_HostApiTypeIdToHostApiIndex( paMME ) )->defaultOutputDevice;
	if( argc >= 3 ){
		sscanf( argv[1], "%d", &deviceIndex );
	}

	printf( "using device id %d (%s)\n", deviceIndex, Pa_GetDeviceInfo(deviceIndex)->name );

    
    outputParameters.device = deviceIndex;
    outputParameters.channelCount = CHANNEL_COUNT;
    outputParameters.sampleFormat = paInt16; /* IMPORTANT must use paInt16 for WMME AC3 */
    outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency;
    outputParameters.hostApiSpecificStreamInfo = NULL;

    wmmeStreamInfo.size = sizeof(PaWinMmeStreamInfo);
    wmmeStreamInfo.hostApiType = paMME; 
    wmmeStreamInfo.version = 1;
    wmmeStreamInfo.flags = paWinMmeWaveFormatDolbyAc3Spdif;
    outputParameters.hostApiSpecificStreamInfo = &wmmeStreamInfo;


	if( Pa_IsFormatSupported( 0, &outputParameters, SAMPLE_RATE ) == paFormatIsSupported  ){
		printf( "Pa_IsFormatSupported reports device will support %d channels.\n", CHANNEL_COUNT );
	}else{
		printf( "Pa_IsFormatSupported reports device will not support %d channels.\n", CHANNEL_COUNT );
	}

    err = Pa_OpenStream(
              &stream,
              NULL, /* no input */
              &outputParameters,
              SAMPLE_RATE,
              FRAMES_PER_BUFFER,
              0,
              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();
    free( data.buffer );
    printf("Test finished.\n");
    
    return err;
error:
    Pa_Terminate();
    free( data.buffer );

    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;
}
コード例 #3
0
int main(void)
{
    PaStream *stream;
    PaStreamParameters outputParameters;
    PaError err;
    paTestData data;
    int i;
    printf("Play different tone sine waves that alternate between left and right channel.\n");
    printf("The low tone should be on the left channel.\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;
    data.currentBalance = 0.0;
    data.targetBalance = 0.0;

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

    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 = 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,
                         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 several seconds.\n");
    for( i=0; i<4; i++ )
    {
		printf("Hear low sound on left side.\n");
		data.targetBalance = 0.01;
        Pa_Sleep( 1000 );
		
		printf("Hear high sound on right side.\n");
		data.targetBalance = 0.99;
        Pa_Sleep( 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;
}
コード例 #4
0
ファイル: kv_server.c プロジェクト: AmitShah/quiet-lwip
int main(int argc, char **argv) {
    PaError err = Pa_Initialize();
    if (err != paNoError) {
        printf("failed to initialize port audio, %s\n", Pa_GetErrorText(err));
        return 1;
    }

    quiet_lwip_portaudio_driver_config *conf =
        calloc(1, sizeof(quiet_lwip_portaudio_driver_config));
    const char *encoder_key = "audible-7k-channel-1";
    const char *decoder_key = "audible-7k-channel-0";
    const char *fname = "/usr/local/share/quiet/quiet-profiles.json";
    conf->encoder_opt =
        quiet_encoder_profile_filename(fname, encoder_key);
    conf->decoder_opt =
        quiet_decoder_profile_filename(fname, decoder_key);

    conf->encoder_device = Pa_GetDefaultOutputDevice();
    const PaDeviceInfo *device_info = Pa_GetDeviceInfo(conf->encoder_device);
    conf->encoder_sample_rate = device_info->defaultSampleRate;
    conf->encoder_latency = device_info->defaultLowOutputLatency;

    conf->decoder_device = Pa_GetDefaultInputDevice();
    device_info = Pa_GetDeviceInfo(conf->decoder_device);
    conf->decoder_sample_rate = device_info->defaultSampleRate;
    conf->decoder_latency = device_info->defaultLowOutputLatency;

    conf->encoder_sample_size = 1 << 8;
    conf->decoder_sample_size = 1 << 8;

    memcpy(conf->hardware_addr, mac, 6);
    quiet_lwip_portaudio_interface *interface =
        quiet_lwip_portaudio_create(conf, htonl(ipaddr), htonl(netmask), htonl(gateway));
    free(conf);

    quiet_lwip_portaudio_audio_threads *audio_threads =
        quiet_lwip_portaudio_start_audio_threads(interface);

    key_value_t *kv = key_value_init();
    kv_t temp_kv;
    temp_kv.key = calloc(key_len, sizeof(uint8_t));
    temp_kv.value = calloc(value_len, sizeof(uint8_t));

    int recv_socket = open_recv(ipaddr_s);

    size_t buf_len = 4096;
    uint8_t *buf = calloc(buf_len, sizeof(uint8_t));

    struct sockaddr_in recv_from;
    int conn_fd = recv_connection(recv_socket, &recv_from);
    printf("received connection from %s\n", inet_ntoa(recv_from.sin_addr.s_addr));

    for (;;) {
        ssize_t recv_len = read(conn_fd, buf, buf_len);
        if (recv_len) {
            printf("received packet from %s: %.*s\n", inet_ntoa(recv_from.sin_addr.s_addr), (int)recv_len, buf);
        } else {
            close(conn_fd);
            conn_fd = recv_connection(recv_socket, &recv_from);
            printf("received connection from %s\n", inet_ntoa(recv_from.sin_addr.s_addr));
            continue;
        }

        if (recv_len < 0) {
            printf("read from connection failed\n");
        }

        if (memcmp(buf, recv_ping_str, strlen(recv_ping_str)) == 0) {
            printf("sending response to %s\n", inet_ntoa(recv_from.sin_addr.s_addr));
            memset(buf, 0, buf_len);
            memcpy(buf, send_ping_str, strlen(send_ping_str));
            write(conn_fd, buf, strlen(send_ping_str));
        } else if (memcmp(buf, recv_add_str, strlen(recv_add_str)) == 0) {
            ptrdiff_t key_offset = strlen(recv_add_str);
            size_t remaining = recv_len - key_offset;
            ptrdiff_t value_offset = 0;
            for (size_t i = 0; i < (remaining - 1) && i < key_len; i++) {
                if (buf[key_offset + i] == add_delim) {
                    value_offset = key_offset + i + 1;
                    break;
                }
            }

            if (value_offset) {
                memset(temp_kv.key, 0, key_len * sizeof(uint8_t));
                memset(temp_kv.value, 0, value_len * sizeof(uint8_t));
                memcpy(temp_kv.key, buf + key_offset, value_offset - key_offset - 1);
                memcpy(temp_kv.value, buf + value_offset, recv_len - value_offset);
                key_value_add(kv, &temp_kv);
                key_value_print(kv);

                memset(buf, 0, buf_len);
                memcpy(buf, send_add_str, strlen(send_add_str));
                write(conn_fd, buf, strlen(send_add_str));
            }
        } else if (memcmp(buf, recv_get_str, strlen(recv_get_str)) == 0) {
            ptrdiff_t key_offset = strlen(recv_get_str);
            memset(temp_kv.key, 0, key_len * sizeof(uint8_t));
            memcpy(temp_kv.key, buf + key_offset, recv_len - key_offset);

            const kv_t *found = key_value_find(kv, &temp_kv);
            if (found) {
                write(conn_fd, found->value, value_len);
            } else {
                write(conn_fd, get_notfound, strlen(get_notfound));
            }
        }

    }

    quiet_lwip_portaudio_stop_audio_threads(audio_threads);
    key_value_destroy(kv);
    free(buf);
    quiet_lwip_portaudio_destroy(interface);

    Pa_Terminate();

    return 0;
}
コード例 #5
0
ファイル: pa_maxsines.cpp プロジェクト: sibosop/smolek
int main(void)
{
	int                 i;
    PaStream*           stream;
    PaStreamParameters  outputParameters;
    PaError             err;
    paTestData          data = {0};
    double              load;

    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.sine[TABLE_SIZE] = data.sine[0]; /* set guard point */

    err = Pa_Initialize();
    if( err != paNoError )
        goto error;
    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              = paFloat32;                   /* 32 bit floating point output. */
    outputParameters.hostApiSpecificStreamInfo = NULL;
    outputParameters.suggestedLatency          = Pa_GetDeviceInfo(outputParameters.device)
                                                 ->defaultHighOutputLatency;
    err = Pa_OpenStream(&stream,
                        NULL,               /* no input */
                        &outputParameters,
                        SAMPLE_RATE,
                        FRAMES_PER_BUFFER,
                        paClipOff,          /* No out of range samples should occur. */
                        patestCallback,
                        &data);
    if( err != paNoError )
        goto error;

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

    /* Play an increasing number of sine waves until we hit MAX_USAGE */
    do  {
        data.numSines++;
        Pa_Sleep(200);
        load = Pa_GetStreamCpuLoad(stream);
        printf("numSines = %d, CPU load = %f\n", data.numSines, load );
        fflush(stdout);
        } while((load < MAX_USAGE) && (data.numSines < MAX_SINES));

    Pa_Sleep(2000);     /* Stay for 2 seconds around 80% CPU. */

    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;
}
コード例 #6
0
static PaCtx *
pa_phone_setup(void) {
  PaCtx		*ctx;
  int		err, i, srcerr;
  PaError	err2;

  err = paNoError;
  err2 = 0;
  
  if ((ctx = calloc(1, sizeof(PaCtx))) == NULL) {
    WHY("Unable to allocate PA context");
    err2 = 1;
    goto error;
  }

  /* Init mutex */
  if (pthread_mutex_init(&ctx->mtx, NULL) != 0) {
    WHYF("Unable to init mutex: %s\n", strerror(errno));
    err2 = 1;
    goto error;
  }
  
  /* Allocate FIFOs */
  i = IN_FRAMES * 10 * sizeof(int16_t);
  printf("Allocating %d byte FIFOs\n", i);
    
  if ((ctx->incoming = fifo_alloc(i)) == NULL) {
    WHY("Unable to allocate incoming FIFO\n");
    err2 = 1;
    goto error;    
  }

  if ((ctx->incrate = fifo_alloc(i)) == NULL) {
    WHY("Unable to allocate incoming SRC FIFO\n");
    err2 = 1;
    goto error;
  }

  if ((ctx->outgoing = fifo_alloc(i)) == NULL) {
    WHY("Unable to allocate outgoing FIFO\n");
    err2 = 1;
    goto error;
  }    


  /* Init sample rate converter */
  if ((ctx->src = src_new(SRC_SINC_BEST_QUALITY, 1, &srcerr)) == NULL) {
    WHYF("Unable to init sample rate converter: %d\n", srcerr);
    err2 = 1;
    goto error;
  }

  /* Init echo canceller */
  if ((ctx->echocan = echo_can_init(ECHO_LEN, ADAPT_MODE)) == NULL) {
    WHY("Unable to init echo canceller\n");
    err2 = 1;
    goto error;
  }

  /* Init codec2 */
  if ((ctx->codec2 = codec2_create()) == NULL) {
    WHY("Unable to init codec2\n");
    err2 = 1;
    goto error;
  }
    
  /* Initialize Port Audio library */
  if ((err = Pa_Initialize()) != paNoError)
    goto error;
     
  /* Open an audio I/O stream. */
  if ((err = Pa_OpenDefaultStream(&ctx->stream,
				  1,          /* input channels */
				  1,          /* output channels */
				  paInt16,
				  SAMPLE_RATE,
				  IN_FRAMES, /* frames per buffer */
				  patestCallback,
				  &ctx)) != paNoError)
    goto error;
 
  /* Start stream */
  if ((err = Pa_StartStream(ctx->stream)) != paNoError)
    goto error;

  /* Close down stream, PA, etc */
/* XXX: hangs in pthread_join on Ubuntu 10.04 */
#ifndef linux
  if ((err = Pa_StopStream(ctx->stream)) != paNoError)
    goto error;
#endif

  /* Do stuff */

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

  error:
  Pa_Terminate();
    
  /* Free things */
  freectx(ctx);
    
  if (err != paNoError)
    WHYF("Port audio error: %s\n", Pa_GetErrorText(err));

  return NULL;
}
コード例 #7
0
ファイル: debug_srate.c プロジェクト: Kirushanr/audacity
int main(void)
{
    PaError    err;
    paTestData data = { 0 };
    long       i;
    double     rate;
    const    PaDeviceInfo *pdi;

    PortAudioStream *outputStream;
    PortAudioStream *inputStream;

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


    pdi = Pa_GetDeviceInfo( INPUT_DEVICE_ID );
    printf("Input device  = %s\n", pdi->name );
    pdi = Pa_GetDeviceInfo( OUTPUT_DEVICE_ID );
    printf("Output device = %s\n", pdi->name );

/* Open input stream. */
    err = Pa_OpenStream(
              &inputStream,
              INPUT_DEVICE_ID,
              SAMPLES_PER_FRAME,               /* stereo input */
              PA_SAMPLE_TYPE,
              NULL,
              paNoDevice,
              0,
              PA_SAMPLE_TYPE,
              NULL,
              INPUT_SAMPLE_RATE,
              FRAMES_PER_BUFFER,            /* frames per buffer */
              NUM_REC_BUFS,               /* number of buffers, if zero then use default minimum */
              paClipOff,       /* we won't output out of range samples so don't bother clipping them */
              recordCallback,
              &data );
    if( err != paNoError ) goto error;

    err = Pa_OpenStream(
              &outputStream,
              paNoDevice,
              0,               /* NO input */
              PA_SAMPLE_TYPE,
              NULL,
              OUTPUT_DEVICE_ID,
              SAMPLES_PER_FRAME,               /* stereo output */
              PA_SAMPLE_TYPE,
              NULL,
              OUTPUT_SAMPLE_RATE,
              FRAMES_PER_BUFFER,            /* frames per buffer */
              0,               /* number of buffers, if zero then use default minimum */
              paClipOff,       /* we won't output out of range samples so don't bother clipping them */
              playCallback,
              &data );
    if( err != paNoError ) goto error;

/* Record and playback multiple times. */
    for( i=0; i<2; i++ )
    {
        printf("Measuring INPUT ------------------------- \n");
        err = MeasureStreamRate( inputStream, &data, &rate );
        if( err != paNoError ) goto error;
        ReportRate( rate, INPUT_SAMPLE_RATE );

        printf("Measuring OUTPUT ------------------------- \n");
        err = MeasureStreamRate( outputStream, &data, &rate );
        if( err != paNoError ) goto error;
        ReportRate( rate, OUTPUT_SAMPLE_RATE );
    }

/* Clean up. */
    err = Pa_CloseStream( inputStream );
    if( err != paNoError ) goto error;

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

    if( err != paNoError ) goto error;

    Pa_Terminate();
    
    printf("Test complete.\n"); fflush(stdout);
    return 0;

error:
    Pa_Terminate();
    fprintf( stderr, "An error occured while using the portaudio stream\n" );
    fprintf( stderr, "Error number: %d\n", err );
    fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) );
    if( err == paHostError )
    {
        fprintf( stderr, "Host Error number: %d\n", Pa_GetHostError() );
    }
    return -1;
}
コード例 #8
0
ファイル: portaudio_client.cpp プロジェクト: nebogeo/red-king
bool portaudio_client::attach(const string &client_name, const device_options &dopt)
{
	if (m_attached) return true;

    PaError err;
	err = Pa_Initialize();
    if( err != paNoError )
 	{
		cerr<<"could not init portaudio_client"<<endl;
        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 ) );
	}

    PaStreamParameters output_parameters;
    output_parameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
    if (output_parameters.device == paNoDevice) {
		cerr<<"error: no default output device."<<endl;
    }
    output_parameters.channelCount = 2;       /* stereo output */
    output_parameters.sampleFormat = paFloat32; /* 32 bit floating point output */
    output_parameters.suggestedLatency = Pa_GetDeviceInfo( output_parameters.device )->defaultLowOutputLatency;
    output_parameters.hostApiSpecificStreamInfo = NULL;

    PaStreamParameters input_parameters;
    input_parameters.device = Pa_GetDefaultInputDevice(); /* default output device */
    if (input_parameters.device == paNoDevice) {
		cerr<<"error: no default input device."<<endl;
    }
    input_parameters.channelCount = 2;       /* stereo output */
    input_parameters.sampleFormat = paFloat32; /* 32 bit floating point output */
    input_parameters.suggestedLatency = Pa_GetDeviceInfo( input_parameters.device )->defaultLowInputLatency;
    input_parameters.hostApiSpecificStreamInfo = NULL;

    PaStream *stream;

    err = Pa_OpenStream(
              &stream,
              NULL, //&input_parameters,
              &output_parameters,
              dopt.samplerate,
              dopt.buffer_size,
              paClipOff,
              process,
              NULL);

    if( err != paNoError )
	{
		cerr<<"could not attach portaudio_client: "<<Pa_GetErrorText( err )<<endl;
		Pa_Terminate();
		return false;
	}

	err = Pa_StartStream(stream);

	if( err != paNoError )
	{
		cerr<<"could not start stream: "<<Pa_GetErrorText( err )<<endl;
		Pa_Terminate();
		return false;
	}

	m_attached=true;
	cerr<<"connected to portaudio..."<<endl;
	return true;
}
コード例 #9
0
int initPlayerOutput() {
	PaError ret = Pa_Initialize();
	if(ret != paNoError)
		Py_FatalError("PortAudio init failed");
	return 0;
}
コード例 #10
0
ファイル: patest_sine.c プロジェクト: dhull2/squeezeslave
int main(void)
{
    PaStreamParameters outputParameters;
    PaStream *stream;
    PaError err;
    paTestData data;
	const PaDeviceInfo *device;
	PaWasapiDeviceRole role;
    int i;
	PaWasapiStreamInfo ws_info = { 0 };

    
    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;

	for (i = 0; i < Pa_GetDeviceCount(); ++i)
	{
		device = Pa_GetDeviceInfo(i);

		if (Pa_GetDeviceInfo(i)->maxInputChannels != 0)
			continue;
		if (Pa_GetDeviceInfo(i)->hostApi != Pa_HostApiTypeIdToHostApiIndex(paWASAPI))
			continue;

		role = PaWasapi_GetDeviceRole(i);
		if (role == eRoleSpeakers)
			break;
	}
	if (role != eRoleSpeakers)
	{
		fprintf(stderr,"Error: No WASAPI Speakers.\n");
		return -1;
	}

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

	ws_info.size		= sizeof(ws_info);
	ws_info.hostApiType = paWASAPI;
	ws_info.version		= 1;
	ws_info.flags		= paWinWasapiExclusive;

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

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

    sprintf( data.message, "No Message" );
    err = Pa_SetStreamFinishedCallback( stream, &StreamFinished );
    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 );

	//while (1) { Pa_Sleep(2); }

    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;
}
コード例 #11
0
ファイル: audiodevice_pa.cpp プロジェクト: crafn/clover
void PaAudioDevice::chooseWiselyAndCreateNicely(){
	PaError err= Pa_Initialize();

	if(err != paNoError)
		throw global::Exception("AudioDevice::chooseWiselyAndCreateNicely(): PortAudio init failed: %s",  Pa_GetErrorText( err ));

	int32 host_api_count= Pa_GetHostApiCount();
	if (host_api_count < 1)
		throw global::Exception("PortAudio host api count: %i", host_api_count);

	// Look for all audio devices
	int32 num_devices;
	num_devices = Pa_GetDeviceCount();
	if(num_devices < 0) {
		throw global::Exception("AudioDevice::chooseWiselyAndCreateNicely(): Pa_GetDeviceCount failed: %s", Pa_GetErrorText(num_devices));
	} else if (num_devices == 0) {
		throw global::Exception("No audio devices");
	} else {
		print(debug::Ch::Audio, debug::Vb::Trivial, "Available audio devices:");
		const PaDeviceInfo *device_info;

		for(int32 i=0; i<num_devices; i++) {
			device_info = Pa_GetDeviceInfo(i);

			print(debug::Ch::Audio, debug::Vb::Trivial, "	 %s", device_info->name);
			print(debug::Ch::Audio, debug::Vb::Trivial, "		 Low latency: %f", device_info->defaultLowOutputLatency);
			print(debug::Ch::Audio, debug::Vb::Trivial, "		 High latency: %f", device_info->defaultHighOutputLatency);
		}

		util::DynArray<int32> device_ids;
		defaultDeviceDId= -1;

		PaStreamParameters output_params= getDefaultStreamParameters();

		util::DynArray<util::Str8> preferred;
		util::Str8 user_preference= global::g_env.cfg->get<util::Str8>("hardware::audioDevice", "");
		if (!user_preference.empty())
			preferred.pushBack(user_preference);

		preferred.pushBack("default");
		preferred.pushBack("Microsoft Sound Mapper - Output");

		// Find supported devices
		for (int32 i=0; i<num_devices; i++) {
			device_info= Pa_GetDeviceInfo(i);
			output_params.device= i;

			err = Pa_IsFormatSupported(0, &output_params, defaultSampleRate);
			if(err == paFormatIsSupported) {
				device_ids.pushBack(i);
			}
		}

		// Find preferred out of supported
		for (auto& m : preferred){
			auto it=
				std::find_if(device_ids.begin(), device_ids.end(),
					[&m](int32 id){
						if(util::Str8(Pa_GetDeviceInfo(id)->name).lowerCased() == m.lowerCased())
							return true;
						return false;
					}
				);

			if (it != device_ids.end()){
				defaultDeviceDId= *it;
				break;
			}
		}

		// Pick first if no match
		if (defaultDeviceDId == -1){
			for (int32 i : device_ids){
				defaultDeviceDId= i;
				break;
			}
		}

		// Error if no supported devices
		if (defaultDeviceDId == -1)
			throw global::Exception("Sufficient audio device not found");

		device_info= Pa_GetDeviceInfo(defaultDeviceDId);

		print(debug::Ch::Audio, debug::Vb::Trivial, "-> %s\n	With suggested latency: %ims",
					device_info->name,
					(int)(output_params.suggestedLatency*1000));
	}
}
コード例 #12
0
int main(void)
{
    PaError    err;
    paTestData data = { 0 };
    long       totalFrames;
    long       numBytes;
    long       i;
    printf("patest_record.c\n"); fflush(stdout);

/* Set up test data structure and sample array. */
    data.frameIndex = 0;
    data.samplesPerFrame = 2;
    data.maxFrameIndex = totalFrames = NUM_SECONDS*SAMPLE_RATE;

    printf("totalFrames = %d\n", totalFrames ); fflush(stdout);
    data.numSamples = totalFrames * data.samplesPerFrame;

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

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

/* Record and playback multiple times. */
    for( i=0; i<2; i++ )
    {
        err = TestRecording( &data );
        if( err != paNoError ) goto error;

        err = TestPlayback( &data );
        if( err != paNoError ) goto error;
    }

/* Clean up. */
    err = Pa_CloseStream( data.inputStream );
    if( err != paNoError ) goto error;

    err = Pa_CloseStream( data.outputStream );
    if( err != paNoError ) goto error;

    if( err != paNoError ) goto error;

    free( data.recordedSamples );
    Pa_Terminate();
    
    printf("Test complete.\n"); fflush(stdout);
    return 0;

error:
    Pa_Terminate();
    fprintf( stderr, "An error occured while using the portaudio stream\n" );
    fprintf( stderr, "Error number: %d\n", err );
    fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) );
    if( err == paHostError )
    {
        fprintf( stderr, "Host Error number: %d\n", Pa_GetHostError() );
    }
    return -1;
}
コード例 #13
0
ファイル: hellodelay.c プロジェクト: srejv/dspplayground
void init_stuff()
{
    float frequency, dgain, dfeedback, dur;
    int i,id;
    const PaDeviceInfo  *info;
    const PaHostApiInfo *hostapi;
    PaStreamParameters outputParameters, inputParameters;
    
    printf("Type the modulator frequency in Hertz: ");
    scanf("%f", &frequency);                        /* get the modulator frequency */

    gtable = new_square(1024, 2);
    osc = new_oscilt(SAMPLING_RATE, gtable, 0.0);

    si = TWO_PI * frequency / SAMPLING_RATE;       /* calculate sampling increment */
    
    freq = frequency;

    
    printf("Type the duration of the delay: ");
    scanf("%f", &dur);                        /* get the modulator frequency */

    printf("Type the gain for the delay: ");
    scanf("%f", &dgain);                        /* get the modulator frequency */
    
    printf("Type the feedback for the delay: ");
    scanf("%f", &dfeedback);                        /* get the modulator frequency */

    delay = new_delay(dur,SAMPLING_RATE, dgain, dfeedback);

    printf("Initializing Portaudio. Please wait...\n");
    Pa_Initialize();                                       /* initialize portaudio */

    for (i=0;i < Pa_GetDeviceCount(); i++) { 
        info = Pa_GetDeviceInfo(i);         /* get information from current device */
        hostapi = Pa_GetHostApiInfo(info->hostApi); /*get info from curr. host API */

        if (info->maxOutputChannels > 0)         /* if curr device supports output */
            printf("%d: [%s] %s (output)\n",i, hostapi->name, info->name );  
    }
    
    printf("\nType AUDIO output device number: ");
    scanf("%d", &id);                   /* get the output device id from the user */
    info = Pa_GetDeviceInfo(id);       /* get chosen device information structure */
    hostapi = Pa_GetHostApiInfo(info->hostApi);         /* get host API structure */
    printf("Opening AUDIO output device [%s] %s\n", hostapi->name, info->name);

    outputParameters.device = id;                             /* chosen device id */
    outputParameters.channelCount = 2;                           /* stereo output */
    outputParameters.sampleFormat = paFloat32;    /* 32 bit floating point output */
    outputParameters.suggestedLatency = info->defaultLowOutputLatency;/* set default */
    outputParameters.hostApiSpecificStreamInfo = NULL;        /* no specific info */

    for (i=0;i < Pa_GetDeviceCount(); i++) {
        info = Pa_GetDeviceInfo(i);         /* get information from current device */
        hostapi = Pa_GetHostApiInfo(info->hostApi); /*get info from curr. host API */

        if (info->maxInputChannels > 0)           /* if curr device supports input */
            printf("%d: [%s] %s (input)\n",i, hostapi->name, info->name );  
    }
    
    printf("\nType AUDIO input device number: ");
    scanf("%d", &id);                     /* get the input device id from the user */
    info = Pa_GetDeviceInfo(id);        /* get chosen device information structure */
    hostapi = Pa_GetHostApiInfo(info->hostApi);          /* get host API structure */
    printf("Opening AUDIO input device [%s] %s\n", hostapi->name, info->name);

    inputParameters.device = id;                               /* chosen device id */
    inputParameters.channelCount = 2;                              /* stereo input */
    inputParameters.sampleFormat = paFloat32;      /* 32 bit floating point output */
    inputParameters.suggestedLatency = info->defaultLowInputLatency; /*set default */
    inputParameters.hostApiSpecificStreamInfo = NULL;          /* no specific info */

    Pa_OpenStream(               /* open the PaStream object and get its address */
              &audioStream,      /* get the address of the portaudio stream object */
              &inputParameters,  /* provide output parameters */
              &outputParameters, /* provide input parameters */
              SAMPLING_RATE,     /* set sampling rate */
              FRAME_BLOCK_LEN,   /* set frames per buffer */
              paClipOff,         /* set no clip */
              audio_callback,    /* provide the callback function address */
              NULL );            /* provide no data for the callback */

    Pa_StartStream(audioStream); /* start the callback mechanism */
    printf("running... press space bar and enter to exit\n");
}
コード例 #14
0
void CVoiceRecorder::Init(bool bEnabled, unsigned int uiServerSampleRate, unsigned char ucQuality, unsigned int uiBitrate)
{
    m_bEnabled = bEnabled;

    if (!bEnabled)            // If we aren't enabled, don't bother continuing
        return;

    m_CS.Lock();

    // Convert the sample rate we received from the server (0-2) into an actual sample rate
    m_SampleRate = convertServerSampleRate(uiServerSampleRate);
    m_ucQuality = ucQuality;

    // State is awaiting input
    m_VoiceState = VOICESTATE_AWAITING_INPUT;

    // Calculate how many frames we are storing and then the buffer size in bytes
    unsigned int iFramesPerBuffer = (2048 / (32000 / m_SampleRate));
    m_uiBufferSizeBytes = iFramesPerBuffer * sizeof(short);

    // Time of last send, this is used to limit sending
    m_ulTimeOfLastSend = 0;

    // Get the relevant speex mode for the servers sample rate
    const SpeexMode* speexMode = getSpeexModeFromSampleRate();
    m_pSpeexEncoderState = speex_encoder_init(speexMode);

    Pa_Initialize();

    int count = Pa_GetHostApiCount();

    PaStreamParameters inputDevice;
    inputDevice.channelCount = 1;
    inputDevice.device = Pa_GetDefaultInputDevice();
    inputDevice.sampleFormat = paInt16;
    inputDevice.hostApiSpecificStreamInfo = NULL;
    inputDevice.suggestedLatency = 0;

    Pa_OpenStream(&m_pAudioStream, &inputDevice, NULL, m_SampleRate, iFramesPerBuffer, paNoFlag, PACallback, this);

    Pa_StartStream(m_pAudioStream);

    // Initialize our outgoing buffer
    speex_encoder_ctl(m_pSpeexEncoderState, SPEEX_GET_FRAME_SIZE, &m_iSpeexOutgoingFrameSampleCount);
    speex_encoder_ctl(m_pSpeexEncoderState, SPEEX_SET_QUALITY, &m_ucQuality);
    int iBitRate = (int)uiBitrate;
    if (iBitRate)
        speex_encoder_ctl(m_pSpeexEncoderState, SPEEX_SET_BITRATE, &iBitRate);

    m_pOutgoingBuffer = (char*)malloc(m_uiBufferSizeBytes * FRAME_OUTGOING_BUFFER_COUNT);
    m_uiOutgoingReadIndex = 0;
    m_uiOutgoingWriteIndex = 0;

    // Initialise the speex preprocessor
    int iSamplingRate;
    speex_encoder_ctl(m_pSpeexEncoderState, SPEEX_GET_SAMPLING_RATE, &iSamplingRate);
    m_pSpeexPreprocState = speex_preprocess_state_init(m_iSpeexOutgoingFrameSampleCount, iSamplingRate);

    // Set our preprocessor parameters
    int iEnable = 1;
    int iDisable = 0;
    speex_preprocess_ctl(m_pSpeexPreprocState, SPEEX_PREPROCESS_SET_AGC, &iEnable);
    speex_preprocess_ctl(m_pSpeexPreprocState, SPEEX_PREPROCESS_SET_DENOISE, &iEnable);
    speex_preprocess_ctl(m_pSpeexPreprocState, SPEEX_PREPROCESS_SET_DEREVERB, &iEnable);
    speex_preprocess_ctl(m_pSpeexPreprocState, SPEEX_PREPROCESS_SET_VAD, &iDisable);
    speex_encoder_ctl(m_pSpeexEncoderState, SPEEX_SET_DTX, &iEnable);

    speex_encoder_ctl(m_pSpeexEncoderState, SPEEX_GET_BITRATE, &iBitRate);

    g_pCore->GetConsole()->Printf("Server Voice Chat Quality [%i];  Sample Rate: [%iHz]; Bitrate [%ibps]", m_ucQuality, iSamplingRate, iBitRate);

    m_CS.Unlock();
}
コード例 #15
0
ファイル: octaveless.c プロジェクト: jeffkaufman/octaveless
int main(void)
{
    PaStreamParameters outputParameters;
    PaStream *stream;
    PaError err;
    paTestData data;
    int i;

    printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d\n",
           SAMPLE_RATE, FRAMES_PER_BUFFER);

    data.phase = 0;
    for (i = 0 ; i < 12 ; i++) {
      data.amplitudes[i] = 0;
      data.states[i] = DECAY;
    }

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

    outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
    if (outputParameters.device == paNoDevice) {
      fprintf(stderr,"Error: No default output device.\n");
      goto error;
    }
    outputParameters.channelCount = 1;       /* mono 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 */
              patestCallback,
              &data );
    if( err != paNoError ) goto error;

    sprintf( data.message, "No Message" );
    err = Pa_SetStreamFinishedCallback( stream, &StreamFinished );
    if( err != paNoError ) goto error;

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

    /* set up unbuffered reading */
    struct termios tio;
    tcgetattr(1,&tio);
    tio.c_lflag &=(~ICANON & ~ECHO);
    tcsetattr(1,TCSANOW,&tio);

    int pressed = -1;
    while(1) {
      switch (getc(stdin)) {
      case 'C':
        pressed = 0;
        break;
      case 'd':
        pressed = 1;
        break;
      case 'D':
        pressed = 2;
        break;
      case 'e':
        pressed = 3;
        break;
      case 'E':
        pressed = 4;
        break;
      case 'F':
        pressed = 5;
        break;
      case 'g':
        pressed = 6;
        break;
      case 'G':
        pressed = 7;
        break;
      case 'a':
        pressed = 8;
        break;
      case 'A':
        pressed = 9;
        break;
      case 'b':
        pressed = 10;
        break;
      case 'B':
        pressed = 11;
        break;
      }

      if (pressed != -1) {
        data.states[pressed] = ATTACK;
      }
    }

    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;
}
コード例 #16
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 */
    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 */
    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;
}
コード例 #17
0
int main(void)
{
    PaStreamParameters outputParameters;
    PaStream *stream;
    PaError err;
    int safeSineCount, stressedSineCount;
    int safeUnderflowCount, stressedUnderflowCount;
    paTestData data = {0};
    double load;


    printf("PortAudio Test: output sine waves, count underflows. SR = %d, BufSize = %d. MAX_LOAD = %f\n",
        SAMPLE_RATE, FRAMES_PER_BUFFER, (float)MAX_LOAD );

    err = Pa_Initialize();
    if( err != paNoError ) goto error;
    
    outputParameters.device = Pa_GetDefaultOutputDevice();  /* default output device */
    outputParameters.channelCount = 1;                      /* mono 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 */
              patestCallback,
              &data );    
    if( err != paNoError ) goto error;
    err = Pa_StartStream( stream );
    if( err != paNoError ) goto error;

    printf("Establishing load conditions...\n" );

    /* Determine number of sines required to get to 50% */
    do
    {
        data.sineCount++;
        Pa_Sleep( 100 );

        load = Pa_GetStreamCpuLoad( stream );
        printf("sineCount = %d, CPU load = %f\n", data.sineCount, load );
    }
    while( load < 0.5 && data.sineCount < (MAX_SINES-1));

    safeSineCount = data.sineCount;

    /* Calculate target stress value then ramp up to that level*/
    stressedSineCount = (int) (2.0 * data.sineCount * MAX_LOAD );
    if( stressedSineCount > MAX_SINES )
        stressedSineCount = MAX_SINES;
    for( ; data.sineCount < stressedSineCount; data.sineCount++ )
    {
        Pa_Sleep( 100 );
        load = Pa_GetStreamCpuLoad( stream );
        printf("STRESSING: sineCount = %d, CPU load = %f\n", data.sineCount, load );
    }
    
    printf("Counting underflows for 5 seconds.\n");
    data.countUnderflows = 1;
    Pa_Sleep( 5000 );

    stressedUnderflowCount = data.outputUnderflowCount;

    data.countUnderflows = 0;
    data.sineCount = safeSineCount;

    printf("Resuming safe load...\n");
    Pa_Sleep( 1500 );
    data.outputUnderflowCount = 0;
    Pa_Sleep( 1500 );
    load = Pa_GetStreamCpuLoad( stream );
    printf("sineCount = %d, CPU load = %f\n", data.sineCount, load );

    printf("Counting underflows for 5 seconds.\n");
    data.countUnderflows = 1;
    Pa_Sleep( 5000 );

    safeUnderflowCount = data.outputUnderflowCount;
    
    printf("Stop stream.\n");
    err = Pa_StopStream( stream );
    if( err != paNoError ) goto error;
    
    err = Pa_CloseStream( stream );
    if( err != paNoError ) goto error;
    
    Pa_Terminate();

    if( stressedUnderflowCount == 0 )
        printf("Test failed, no output underflows detected under stress.\n");
    else if( safeUnderflowCount != 0 )
        printf("Test failed, %d unexpected underflows detected under safe load.\n", safeUnderflowCount);
    else
        printf("Test passed, %d expected output underflows detected under stress, 0 unexpected underflows detected under safe load.\n", stressedUnderflowCount );

    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
int main(void)
{
    PaStreamParameters outputParameters;
    PaStream *stream;
    PaError err;
    TestData data;
    int i, j;


    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. );
    }

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

    outputParameters.device = 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,      /* output will be in-range, so no need to clip */
              TestCallback,
              &data );
    if( err != paNoError ) goto error;

    printf("Repeating test %d times.\n", NUM_LOOPS );

    for( i=0; i < NUM_LOOPS; ++i )
    {
        data.phase = 0;
        data.generatedFramesCount = 0;
        data.callbackReturnedPaComplete = 0;
        data.callbackInvokedAfterReturningPaComplete = 0;

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

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

        /* wait for the callback to complete generating NUM_SECONDS of tone */

        do
        {
            Pa_Sleep( 500 );
        }
        while( !data.callbackReturnedPaComplete );

        printf( "Callback returned paComplete.\n" );
        printf( "Waiting for buffers to finish playing...\n" );

        /* wait for stream to become inactive,
           or for a timeout of approximately NUM_SECONDS
         */

        j = 0;
        while( Pa_IsStreamActive( stream ) && j < NUM_SECONDS * 2 )
        {
            printf(".\n" );
            Pa_Sleep( 500 );
            ++j;
        }

        if( Pa_IsStreamActive( stream ) )
        {
            printf( "TEST FAILED: Timed out waiting for buffers to finish playing.\n" );
        }
        else
        {
            printf("Buffers finished.\n" );
        }

        if( data.callbackInvokedAfterReturningPaComplete )
        {
            printf( "TEST FAILED: Callback was invoked after returning paComplete.\n" );
        }


        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;
}
コード例 #19
0
int main(void)
{
    PaStreamParameters outputParameters;
    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;

    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 */
              patestCallback,
              &data );
    if( err != paNoError ) goto error;

    sprintf( data.message, "No Message" );
    err = Pa_SetStreamFinishedCallback( stream, &StreamFinished );
    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;
}
コード例 #20
0
ファイル: Kernel.c プロジェクト: joelolofsson/DAT096
int main(void)
{
    
    /***************************************************************
     Set up the hardware parameters
     ****************************************************************/
    
    PaStreamParameters inputParameters, outputParameters;
    PaStream *stream;
    PaError err;
    
    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 = 1;       /* Single channel 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 = 1;       /* Single channel output */
    outputParameters.sampleFormat = PA_SAMPLE_TYPE;
    outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency;
    outputParameters.hostApiSpecificStreamInfo = NULL;
    
    tempOutput =(float*)malloc(FRAMES_PER_BUFFER*sizeof(float));
    
    audioKernelSamples = (int16_t*)malloc(FRAMES_PER_BUFFER*sizeof(int16_t));
    
    
    /***************************************************************
     Initialize the effects from the soundbox!
     ****************************************************************/
    
    /////////////EQ///////////////
    gainL = 12.00f;
    gainM = 0.00f;
    gainH = 0.00f;
    fcL = 300.0f;
    fcM = 800.0f;
    fcH = 8000.0f;
    QL = 0.7f;
    QM =2.0f;
    QH =0.7f;
    /////////////////////////////
    
    /////////////delay///////////
    feedback_d = 100;
    time_d= 32;
    level_d = 127;
    /////////////////////////////
    
    ///////////Chorus///////////
    rate_c= 200;
    depth_c = 8;
    level_c = 127;
    type_c = LFO_SINE;
    delayLineSize_c =10000;
    ////////////////////////////
    
    /////////Flanger///////////
    rate_f = 32;
    depth_f = 16;
    delay_f = 255;
    level_f = 255;
    type_f = LFO_SINE;
    delayLineSize_f = 10000;
    //////////////////////////
    
    //////Tremolo////////////
    rate_t = 127;
    depth_t = 127;
    level_t = 255;
    type_t = LFO_SINE;
    
    ////////////////////////
    
    //////////Vibrato///////
    rate_v = 255;
    depth_v = 255;
    type_v = LFO_SINE;
    delayLineSize_v = 10000;
    ///////////////////
    
    /////// WAH WAH ///////
    rate_w = 127;
    depth_w = 255;
    res_w = 127;
    type_w = automatic;
    ///////////////////////
    
    /////// Phaser  ///////
    rate_p = 32;
    depth_p = 127;
    res_p = 255;
    ///////////////////////
    
    ///// Distortion /////
    pre_amp_d = 255;
    master_d = 160;
    tone_d = 180;
    //////////////////////
    
    
    initialize();
    
    

    /***************************************************************
     Open the stream (The communication to the sound card)
     ****************************************************************/
    
    err = Pa_OpenStream(
                        &stream,
                        &inputParameters,
                        &outputParameters,
                        SAMPLE_RATE,
                        FRAMES_PER_BUFFER,
                        0, /* paClipOff, */  /* we won't output out of range samples so don't bother clipping them */
                        processCallback,
                        NULL );
    
    /***************************************************************
     Error handling code below .......
     ****************************************************************/
    
    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;
    
    printf("Finished. gNumNoInputs = %d\n", gNumNoInputs );
    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;
}
コード例 #21
0
ファイル: config.cpp プロジェクト: pc1cp/pappsdr
GlobalConfig::GlobalConfig()
{
    m_LoggingWindow = new GlobalLogging;
    m_AudioThread = 0;

    // initializing portaudio
    PaError err = Pa_Initialize();

    if( err != paNoError )
    {
        Log( "Error initializing Portaudio: %s", Pa_GetErrorText( err ) );
        exit(-1);
    }

    // get available soundcards from portaudio
    int nDevices;

    nDevices = Pa_GetDeviceCount();
    if( nDevices < 0 )
    {
        Log( "Error, Pa_CountDevices returned : %i", nDevices );
        Log( "Error initializing Portaudio: %s", Pa_GetErrorText( nDevices ));
        exit(-1);
    }
    else
    {
        // Ok, so we got some audio-devices, it's time to test if they support
        // what we need...

        const PaDeviceInfo* DeviceInfo;

        for( int i=0; i<nDevices; i++ )
        {
            DeviceInfo = Pa_GetDeviceInfo( i );
			Log( "Device-Index: %i", i );
			Log( "Device-Name: %s", DeviceInfo->name );
			Log( "Device-Max-Input-Channels: %i", DeviceInfo->maxInputChannels );
			Log( "Device-Max-Output-Channels: %i", DeviceInfo->maxOutputChannels );
			const PaHostApiInfo* HostApiInfo = Pa_GetHostApiInfo( DeviceInfo->hostApi );
			Log( "Device-Host-API: %s", HostApiInfo->name );
			Log( " " );
		}

        // Build up list of usable output devices...
        for( int i=0; i<nDevices; i++ )
        {
            DeviceInfo = Pa_GetDeviceInfo( i );

#ifndef _WIN32
            if( DeviceInfo->maxOutputChannels >= 2 )
            {
                // add audio-device to list of usable audio-devices.
                AudioDevice_t entry;
                entry.Name = wxString::From8BitData(DeviceInfo->name);
                entry.NumericID = i;
                m_AudioOutputDevices.push_back( entry );
            }
#else
			const PaHostApiInfo* HostApiInfo = Pa_GetHostApiInfo( DeviceInfo->hostApi );

            if( DeviceInfo->maxOutputChannels >= 2 &&
				HostApiInfo->type == paWDMKS      )
            {
                // add audio-device to list of usable audio-devices.
                AudioDevice_t entry;
                entry.Name = _("[WDMKS] - ")+wxString::From8BitData(DeviceInfo->name);
                entry.NumericID = i;
                m_AudioOutputDevices.push_back( entry );
            }

            if( DeviceInfo->maxOutputChannels >= 2 &&
				HostApiInfo->type == paWASAPI      )
            {
                // add audio-device to list of usable audio-devices.
                AudioDevice_t entry;
                entry.Name = _("[WASAPI] - ")+wxString::From8BitData(DeviceInfo->name);
                entry.NumericID = i;
                m_AudioOutputDevices.push_back( entry );
            }

            if( DeviceInfo->maxOutputChannels >= 2 &&
				HostApiInfo->type == paMME         )
            {
                // add audio-device to list of usable audio-devices.
                AudioDevice_t entry;
                entry.Name = _("[MME] - ")+wxString::From8BitData(DeviceInfo->name);
                entry.NumericID = i;
                m_AudioOutputDevices.push_back( entry );
            }

            if( DeviceInfo->maxOutputChannels >= 2 &&
				HostApiInfo->type == paDirectSound  )
            {
                // add audio-device to list of usable audio-devices.
                AudioDevice_t entry;
                entry.Name = _("[DirectSound] - ")+wxString::From8BitData(DeviceInfo->name);
                entry.NumericID = i;
                m_AudioOutputDevices.push_back( entry );
            }
#endif
        }

        // Build up list of usable input devices...
        for( int i=0; i<nDevices; i++ )
        {
            DeviceInfo = Pa_GetDeviceInfo( i );

#ifndef _WIN32
            if( DeviceInfo->maxInputChannels >= 2 )
            {
                // add audio-device to list of usable audio-devices.
                AudioDevice_t entry;
                entry.Name = wxString::From8BitData(DeviceInfo->name);
                entry.NumericID = i;
                m_AudioInputDevices.push_back( entry );
            }
#else
			const PaHostApiInfo* HostApiInfo = Pa_GetHostApiInfo( DeviceInfo->hostApi );

            if( DeviceInfo->maxInputChannels >= 2 &&
				HostApiInfo->type == paWDMKS      )
            {
                // add audio-device to list of usable audio-devices.
                AudioDevice_t entry;
                entry.Name = _("[WDMKS] - ") + wxString::From8BitData(DeviceInfo->name);
                entry.NumericID = i;
                m_AudioInputDevices.push_back( entry );
            }

            if( DeviceInfo->maxInputChannels >= 2 &&
				HostApiInfo->type == paWASAPI     )
            {
                // add audio-device to list of usable audio-devices.
                AudioDevice_t entry;
                entry.Name = _("[WASAPI] - ") + wxString::From8BitData(DeviceInfo->name);
                entry.NumericID = i;
                m_AudioInputDevices.push_back( entry );
            }

            if( DeviceInfo->maxInputChannels >= 2 &&
				HostApiInfo->type == paMME      )
            {
                // add audio-device to list of usable audio-devices.
                AudioDevice_t entry;
                entry.Name = _("[MME] - ") + wxString::From8BitData(DeviceInfo->name);
                entry.NumericID = i;
                m_AudioInputDevices.push_back( entry );
            }

            if( DeviceInfo->maxInputChannels >= 2 &&
				HostApiInfo->type == paDirectSound )
            {
                // add audio-device to list of usable audio-devices.
                AudioDevice_t entry;
                entry.Name = _("[DirectSound] - ") + wxString::From8BitData(DeviceInfo->name);
                entry.NumericID = i;
                m_AudioInputDevices.push_back( entry );
            }
#endif
        }
    }

    // now try to find out which audio-device was stored the last time
    m_OutputDeviceIndex =  0;
    m_InputDeviceIndex  =  0;
    wxString lastInputDevice = m_Registry.getInputDevice();
    wxString lastOutputDevice = m_Registry.getOutputDevice();

    // and if it's in the current device-list, then choose it again
    for( unsigned int i=0; i<m_AudioInputDevices.size(); i++)
    {
        if( lastInputDevice == m_AudioInputDevices[i].Name )
        {
            Log( "Last-In-Index: %i", m_AudioInputDevices[i].NumericID );
            m_InputDeviceIndex = i;
            break;
        }
    }

    // and if it's in the current device-list, then choose it again
    for( unsigned int i=0; i<m_AudioOutputDevices.size(); i++)
    {
        if( lastOutputDevice == m_AudioOutputDevices[i].Name )
        {
            Log( "Last-Out-Index: %i", m_AudioOutputDevices[i].NumericID );
            m_OutputDeviceIndex = i;
            break;
        }
    }
}
コード例 #22
0
ファイル: debug_multi_in.c プロジェクト: ruthmagnus/audacity
int main(void)
{
    PortAudioStream *stream;
    PaError err;
    paTestData data;
    int i;
    PaDeviceID inputDevice;
    const PaDeviceInfo *pdi;
    printf("PortAudio Test: input signal from each channel. %d buffers\n", NUM_BUFFERS );
    data.liveChannel = 0;
    err = Pa_Initialize();
    if( err != paNoError ) goto error;
#ifdef INPUT_DEVICE_NAME
    printf("Try to use device: %s\n", INPUT_DEVICE_NAME );
    inputDevice = PaFindDeviceByName(INPUT_DEVICE_NAME);
    if( inputDevice == paNoDevice )
    {
        printf("Could not find %s. Using default instead.\n", INPUT_DEVICE_NAME );
        inputDevice = Pa_GetDefaultInputDeviceID();
    }
#else
    printf("Using default input device.\n");
    inputDevice = Pa_GetDefaultInputDeviceID();
#endif
    pdi = Pa_GetDeviceInfo( inputDevice );
    if( pdi == NULL )
    {
        printf("Could not get device info!\n");
        goto error;
    }
    data.numChannels = pdi->maxInputChannels;
    printf("Input Device name is %s\n", pdi->name );
    printf("Input Device has %d channels.\n", pdi->maxInputChannels);
    err = Pa_OpenStream(
              &stream,
              inputDevice,
              pdi->maxInputChannels,
              paFloat32,  /* 32 bit floating point input */
              NULL,
              OUTPUT_DEVICE,
              2,
              paFloat32,  /* 32 bit floating point output */
              NULL,
              SAMPLE_RATE,
              FRAMES_PER_BUFFER,  /* frames per buffer */
              NUM_BUFFERS,    /* number of buffers, if zero then use default minimum */
              paClipOff,      /* we won't output out of range samples so don't bother clipping them */
              patestCallback,
              &data );
    if( err != paNoError ) goto error;
    data.liveChannel = 0;
    err = Pa_StartStream( stream );
    if( err != paNoError ) goto error;
    for( i=0; i<data.numChannels; i++ )
    {
        data.liveChannel = i;
        printf("Channel %d being sent to output. Hit ENTER for next channel.", i );
        fflush(stdout);
        getchar();
    }
    err = Pa_StopStream( stream );
    if( err != paNoError ) goto error;

    err = Pa_CloseStream( stream );
    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;
}
コード例 #23
0
ファイル: pa_devs.c プロジェクト: ruthmagnus/audacity
int main(void)
{
    int     i, numDevices, defaultDisplayed;
    const   PaDeviceInfo *deviceInfo;
    PaStreamParameters inputParameters, outputParameters;
    PaError err;

    
    Pa_Initialize();

    printf( "PortAudio version number = %d\nPortAudio version text = '%s'\n",
            Pa_GetVersion(), Pa_GetVersionText() );

            
    numDevices = Pa_GetDeviceCount();
    if( numDevices < 0 )
    {
        printf( "ERROR: Pa_CountDevices returned 0x%x\n", numDevices );
        err = numDevices;
        goto error;
    }
    
    printf( "Number of devices = %d\n", numDevices );
    for( i=0; i<numDevices; i++ )
    {
        deviceInfo = Pa_GetDeviceInfo( i );
        printf( "--------------------------------------- device #%d\n", i );
                
    /* Mark global and API specific default devices */
        defaultDisplayed = 0;
        if( i == Pa_GetDefaultInputDevice() )
        {
            printf( "[ Default Input" );
            defaultDisplayed = 1;
        }
        else if( i == Pa_GetHostApiInfo( deviceInfo->hostApi )->defaultInputDevice )
        {
            const PaHostApiInfo *hostInfo = Pa_GetHostApiInfo( deviceInfo->hostApi );
            printf( "[ Default %s Input", hostInfo->name );
            defaultDisplayed = 1;
        }
        
        if( i == Pa_GetDefaultOutputDevice() )
        {
            printf( (defaultDisplayed ? "," : "[") );
            printf( " Default Output" );
            defaultDisplayed = 1;
        }
        else if( i == Pa_GetHostApiInfo( deviceInfo->hostApi )->defaultOutputDevice )
        {
            const PaHostApiInfo *hostInfo = Pa_GetHostApiInfo( deviceInfo->hostApi );
            printf( (defaultDisplayed ? "," : "[") );                
            printf( " Default %s Output", hostInfo->name );
            defaultDisplayed = 1;
        }

        if( defaultDisplayed )
            printf( " ]\n" );

    /* print device info fields */
        printf( "Name                        = %s\n", deviceInfo->name );
        printf( "Host API                    = %s\n",  Pa_GetHostApiInfo( deviceInfo->hostApi )->name );
        printf( "Max inputs = %d", deviceInfo->maxInputChannels  );
        printf( ", Max outputs = %d\n", deviceInfo->maxOutputChannels  );

        printf( "Default low input latency   = %8.3f\n", deviceInfo->defaultLowInputLatency  );
        printf( "Default low output latency  = %8.3f\n", deviceInfo->defaultLowOutputLatency  );
        printf( "Default high input latency  = %8.3f\n", deviceInfo->defaultHighInputLatency  );
        printf( "Default high output latency = %8.3f\n", deviceInfo->defaultHighOutputLatency  );

#ifdef WIN32
#ifndef PA_NO_ASIO
/* ASIO specific latency information */
        if( Pa_GetHostApiInfo( deviceInfo->hostApi )->type == paASIO ){
            long minLatency, maxLatency, preferredLatency, granularity;

            err = PaAsio_GetAvailableLatencyValues( i,
		            &minLatency, &maxLatency, &preferredLatency, &granularity );

            printf( "ASIO minimum buffer size    = %ld\n", minLatency  );
            printf( "ASIO maximum buffer size    = %ld\n", maxLatency  );
            printf( "ASIO preferred buffer size  = %ld\n", preferredLatency  );

            if( granularity == -1 )
                printf( "ASIO buffer granularity     = power of 2\n" );
            else
                printf( "ASIO buffer granularity     = %ld\n", granularity  );
        }
#endif /* !PA_NO_ASIO */
#endif /* WIN32 */

        printf( "Default sample rate         = %8.2f\n", deviceInfo->defaultSampleRate );

    /* poll for standard sample rates */
        inputParameters.device = i;
        inputParameters.channelCount = deviceInfo->maxInputChannels;
        inputParameters.sampleFormat = paInt16;
        inputParameters.suggestedLatency = 0; /* ignored by Pa_IsFormatSupported() */
        inputParameters.hostApiSpecificStreamInfo = NULL;
        
        outputParameters.device = i;
        outputParameters.channelCount = deviceInfo->maxOutputChannels;
        outputParameters.sampleFormat = paInt16;
        outputParameters.suggestedLatency = 0; /* ignored by Pa_IsFormatSupported() */
        outputParameters.hostApiSpecificStreamInfo = NULL;

        if( inputParameters.channelCount > 0 )
        {
            printf("Supported standard sample rates\n for half-duplex 16 bit %d channel input = \n",
                    inputParameters.channelCount );
            PrintSupportedStandardSampleRates( &inputParameters, NULL );
        }

        if( outputParameters.channelCount > 0 )
        {
            printf("Supported standard sample rates\n for half-duplex 16 bit %d channel output = \n",
                    outputParameters.channelCount );
            PrintSupportedStandardSampleRates( NULL, &outputParameters );
        }

        if( inputParameters.channelCount > 0 && outputParameters.channelCount > 0 )
        {
            printf("Supported standard sample rates\n for full-duplex 16 bit %d channel input, %d channel output = \n",
                    inputParameters.channelCount, outputParameters.channelCount );
            PrintSupportedStandardSampleRates( &inputParameters, &outputParameters );
        }
    }

    Pa_Terminate();

    printf("----------------------------------------------\n");
    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 err;
}
コード例 #24
0
void audiosource_portaudio::init() {
	err = Pa_Initialize();
	if( err != paNoError ) {
		std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl;
		throw audiosourceexception("Pa_Initialize");
	}

	PaHostApiIndex api_idx;

	const PaHostApiInfo* info = Pa_GetHostApiInfo(Pa_GetDefaultHostApi());

	std::cerr << "Default device: " << info->name << std::endl;

	for (api_idx = 0; api_idx < Pa_GetHostApiCount(); ++api_idx) {
		info = Pa_GetHostApiInfo(api_idx);
		std::cerr << "device " << api_idx << ": " << info->name << std::endl;
	}

	//int frames_per_buffer = get_sample_rate();
	int frames_per_buffer = paFramesPerBufferUnspecified;

	/*
	 * We have two separate streams for input and output to work-around a Debian specific
	 * bug on PortAudio.
	 */

    /* Open an audio I/O stream. */
    err = Pa_OpenDefaultStream( &stream_in,
    							get_in_channel_count(),          /* input channels */
                                0,          /* output */
                                paFloat32,  /* 32 bit floating point output */
                                get_sample_rate(),
                                frames_per_buffer, /* frames per buffer, i.e. the number
                                                   of sample frames that PortAudio will
                                                   request from the callback. Many apps
                                                   may want to use
                                                   paFramesPerBufferUnspecified, which
                                                   tells PortAudio to pick the best,
                                                   possibly changing, buffer size.*/
                                portaudio_in_callback, /* this is your callback function */
                                static_cast<void*>(this) ); /*This is a pointer that will be passed to
                                                   your callback*/
	if( err != paNoError ) {
		std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl;
		throw audiosourceexception("Pa_OpenDefaultStream");
	}

	err = Pa_StartStream( stream_in );
	if( err != paNoError ) {
		std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl;
		throw audiosourceexception("Pa_StartStream");
	}

    /* Open an audio I/O stream. */
    err = Pa_OpenDefaultStream( &stream_out,
    							0,          /* input channels */
    							get_out_channel_count(),          /* output */
                                paFloat32,  /* 32 bit floating point output */
                                get_sample_rate(),
                                frames_per_buffer, /* frames per buffer, i.e. the number
                                                   of sample frames that PortAudio will
                                                   request from the callback. Many apps
                                                   may want to use
                                                   paFramesPerBufferUnspecified, which
                                                   tells PortAudio to pick the best,
                                                   possibly changing, buffer size.*/
                                portaudio_out_callback, /* this is your callback function */
                                static_cast<void*>(this) ); /*This is a pointer that will be passed to
                                                   your callback*/
	if( err != paNoError ) {
		std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl;
		throw audiosourceexception("Pa_OpenDefaultStream");
	}

	err = Pa_StartStream( stream_out );
	if( err != paNoError ) {
		std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl;
		throw audiosourceexception("Pa_StartStream");
	}
}
コード例 #25
0
ファイル: main.cpp プロジェクト: calceusHD/cqtTest
        Main() 
        {
            mScale = 0.1f;
            mOffset = 1.0f;
            mDataOffset = 0;
            isClicked = false;
            screen = Vec2<unsigned int>(800, 600);
            std::setlocale(LC_ALL, "en_US.UTF-8");
            glfwInit();
            glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
            glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
            //glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
            glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
            GLFWwindow* window = glfwCreateWindow(screen.x, screen.y, "test", nullptr, nullptr);
            if (window == nullptr)
            {
                printf("cant create window");
                return;
            }
            
            glfwSetWindowSizeCallback(window, windowSizeCallback);
            glfwSetKeyCallback(window, keyCallback);
            glfwSetMouseButtonCallback(window, clickCallback);
            glfwSetCursorPosCallback(window, mouseCallback);
            glfwMakeContextCurrent(window);
            glewExperimental = true;
            glewInit();
            
            int tmp;

            glGetIntegerv(GL_MAX_ELEMENTS_VERTICES , &tmp);

            std::cout << "GL_MAX_ELEMENTS_VERTICES: " << tmp << std::endl;
            
            int err = Pa_Initialize();
            if (err != paNoError)
                printf("error");
            
            int num = Pa_GetDeviceCount();
            const PaDeviceInfo* devInfo;
            const PaHostApiInfo* apiInfo;
            for (int i = 0; i < num; ++i) {
                devInfo = Pa_GetDeviceInfo(i);
                apiInfo = Pa_GetHostApiInfo(devInfo->hostApi);
                printf("%i, %s on %s\n", i, devInfo->name, apiInfo->name);
            }
            
            
            float sampleRate = 44100.0f;
            
            
            double t = glfwGetTime();
            Kern k(sampleRate, 12, 4 * 16.352f, sampleRate / 2);
            BlockMatrix<std::complex<double>> b(k.K, k.mN0, k.mB, 0.01);
            mAudioData = new double[b.getWidth()];
            mAudioLength = b.getWidth();
            for (unsigned int i = 0; i < mAudioLength; ++i) {
                mAudioData[i] = wave(55, sampleRate, i) + wave(110, sampleRate, i) + wave(220, sampleRate, i)
                        + wave(440, sampleRate, i) + wave(880, sampleRate, i) + wave(1760, sampleRate, i)
                        + wave(3520, sampleRate, i) + wave(7040, sampleRate, i);
            }
            
            printf("kernel time:%f\n", glfwGetTime() - t);
            float drawArray[k.mB * 2];
            std::complex<double> out[k.mB];
            CQT::transform(mAudioData, out, b, mAudioLength);
            t = glfwGetTime();
            
            printf("transform time:%f\n", glfwGetTime() - t);
            
            //glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
            glDebugMessageCallback(debugCallback, nullptr);
            //glEnable(GL_DEBUG_OUTPUT);
                        
            printf("%s\n", glGetString(GL_VERSION));
            Shader fs("res/shader/fragment.c", true, GL_FRAGMENT_SHADER);
            Shader vs("res/shader/vertex.c", true, GL_VERTEX_SHADER);
            Program* p = new Program();
            p->attach(fs);
            p->attach(vs);
            p->build();
            p->use();
            
            Program p2;
            Shader fs2("res/shader/fragment2.c", true, GL_FRAGMENT_SHADER);
            Shader vs2("res/shader/vertex2.c", true, GL_VERTEX_SHADER);
            p2.attach(fs2);
            p2.attach(vs2);
            p2.build();
            p2.use();
            
            int uniformData = p2.getUniformLocation("data");
            
            unsigned int waterfallSize = 512;
            
            tm = new TextureManager();
            
            unsigned int waterfallTexture;
            unsigned int waterfallId = tm->getFreeTexture();
            
            glGenTextures(1, &waterfallTexture);
            glActiveTexture(GL_TEXTURE0 + waterfallId);
            
            glBindTexture( GL_TEXTURE0, waterfallTexture );

            glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
            
            unsigned char* textureTmp = new unsigned char[waterfallSize * b.getWidth()];
            
            glTexImage2D( GL_TEXTURE_2D_ARRAY, 0, GL_R8, b.getWidth(), waterfallSize, 0, GL_RED, GL_UNSIGNED_BYTE, textureTmp);
            
            delete textureTmp;
            
            float max = 0;
            for (unsigned int i = 0; i < k.mB; ++i) {
                    drawArray[2 * i + 0] = (float)i / k.mB * 2.0f - 1.0f;
                    float tmp = std::abs(out[i]);
                    drawArray[2 * i + 1] = tmp;
                    max = std::max(tmp, max);

                }
            
            font = new Font(512, "res/font/DroidSans.woff", 32, tm);
            print = new Print(font);
            //print.set(&font, "res/shader/fontVertex.c", "res/shader/fontFragment.c");
            print->setScreenSize(screen);
            glm::vec2* vert = new glm::vec2[1024];
            
            glm::vec2* debug = new glm::vec2[b.getWidth()];
            for (unsigned int i = 0; i < b.getWidth(); ++i) {
                debug[i].x = (float)i / b.getWidth() * 2.0f - 1.0f;
            }
            uint32_t vao;
            glGenVertexArrays(1, &vao);
            glBindVertexArray(vao);
            uint32_t vbo[2];
            glGenBuffers(1, vbo);
            glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
            glEnableVertexAttribArray(0);
            glBufferData(GL_ARRAY_BUFFER, k.mB * sizeof(glm::vec2), drawArray, GL_DYNAMIC_DRAW);
            glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
            glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
            glEnable(GL_BLEND);
            glfwSetWindowUserPointer(window, this);
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
            
            double time, timeo;
            glfwSwapInterval(1);
            PaStream* stream;
            PaStreamParameters params;
            params.device = 21;
            params.channelCount = 1;
            params.sampleFormat = paFloat32;
            params.hostApiSpecificStreamInfo = nullptr;
            params.suggestedLatency = 0.5;
            
            
            err =  Pa_OpenStream(&stream, &params, nullptr, sampleRate, paFramesPerBufferUnspecified, 0, paCallback, this);
            if (err != paNoError)
                printf("error %i", err);
            Pa_StartStream(stream);
            while(!glfwWindowShouldClose(window))
            {
                timeo = time;
                time = glfwGetTime();
                CQT::transform(mAudioData, out, b, mAudioLength);
            
            
                max = 0.0f;
                for (unsigned int i = 0; i < k.mB; ++i) {
                    drawArray[2 * i + 0] = (float)i / k.mB * 2.0f - 1.0f;
                    float tmp = std::abs(out[i]);
                    drawArray[2 * i + 1] = tmp;
                    max = std::max(tmp, max);

                }
                for (unsigned int i = 0; i < k.mB; ++i) {
                    drawArray[2 * i + 1] = std::log(drawArray[2 * i +1]) * mScale + mOffset;
                }
                //printf("%f\n", drawArray[1]);
                glBindVertexArray(vao);
                glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
                glBufferData(GL_ARRAY_BUFFER, k.mB * sizeof(glm::vec2), drawArray, GL_DYNAMIC_DRAW);
                p->use();
                glDrawArrays(GL_LINE_STRIP, 0, k.mB);
                for (unsigned int i = 0; i < b.getWidth(); ++i) {
                    debug[i].y = mAudioData[i] / 15.0;
                }
                glBufferData(GL_ARRAY_BUFFER, b.getWidth() * sizeof(glm::vec2), debug, GL_DYNAMIC_DRAW);
                glDrawArrays(GL_LINE_STRIP, 0, b.getWidth());
               print->printfAt(-300.0f, 100.0f, 16.0f, 16.0f, u8"Fps:%03.3f", 1/(time-timeo));
                
                glfwSwapBuffers(window);
                glClear(GL_COLOR_BUFFER_BIT);
                glfwPollEvents();
                
            }
            Pa_StopStream(stream);
            Pa_CloseStream(stream);
            Pa_Terminate();

            std::cout << "Hello World. I'm Peach." << std::endl;

        }
コード例 #26
0
/*!
   Start the audio device

 */
void AudioReaderPortAudio::initialize()
{
    initialized     = false;
    bpmax           = sizes.chunk_size / sizes.advance_size;
    inputParameters.device=settings->value(s_sdr_deviceindx,s_sdr_deviceindx_def).toInt();
    switch (settings->value(s_sdr_bits,s_sdr_bits_def).toInt()) {
    case 0:
        inputParameters.sampleFormat = paInt16;
        break;
    case 1:
        inputParameters.sampleFormat = paInt24;
        break;
    case 2:
        inputParameters.sampleFormat = paInt32;
        break;
    }
    inputParameters.channelCount=2;
    inputParameters.hostApiSpecificStreamInfo=NULL;

    if (buff) {
        delete [] buff;
    }
    buff = new unsigned char[sizes.chunk_size];
    for (unsigned long i = 0; i < sizes.chunk_size; i++) {
        buff[i] = 0;
    }
    stream = NULL;
    err    = Pa_Initialize();
    if (checkError(err)) {
        stop();
        return;
    }
    int numDevices = Pa_GetDeviceCount();
    if (numDevices < 0) {
        emit(error("ERROR: PortAudio found no audio devices"));
        return;
    }
    if (Pa_GetDeviceInfo(inputParameters.device)==NULL) {
        emit(error("ERROR: getdeviceinfo returned null pointer"));
        return;
    }
    if (Pa_GetDeviceInfo(inputParameters.device)->maxInputChannels < 2) {
        emit(error("ERROR: audio device does not support stereo"));
        return;
    }
    // set suggested latency
    inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultLowInputLatency;
    periodSize=settings->value(s_sdr_fft,s_sdr_fft_def).toInt()/4;

    err = Pa_IsFormatSupported(&inputParameters, NULL,
                               settings->value(s_sdr_sound_sample_freq,s_sdr_sound_sample_freq_def).toInt());
    if (checkError(err)) {
        stop();
        return;
    }
    err = Pa_OpenStream(
                &stream,
                &inputParameters, NULL,
                settings->value(s_sdr_sound_sample_freq,s_sdr_sound_sample_freq_def).toInt(),
                periodSize,
                paClipOff | paDitherOff,
                callback,
                this);
    if (checkError(err)) {
        stop();
        return;
    }
    err = Pa_StartStream(stream);
    if (checkError(err)) {
        stop();
        return;
    }
    mutex.lock();
    initialized = true;
    running = true;
    mutex.unlock();
}
コード例 #27
0
ファイル: debug_sine_amp.c プロジェクト: Affix/fgcom
int main(void)
{
    char  pad[256];
    PortAudioStream *stream;
    PaError err;
    const PaDeviceInfo *pdi;
    paTestData data = {0};
    printf("PortAudio Test: output sine wave on each channel.\n" );

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

    pdi = Pa_GetDeviceInfo( OUTPUT_DEVICE );
    data.numChannels = pdi->maxOutputChannels;
    if( data.numChannels > MAX_CHANNELS ) data.numChannels = MAX_CHANNELS;
    printf("Number of Channels = %d\n", data.numChannels );
    data.amplitude = 1.0;
    
    err = Pa_OpenStream(
              &stream,
              paNoDevice, /* default input device */
              0,              /* no input */
              paFloat32,  /* 32 bit floating point input */
              NULL,
              OUTPUT_DEVICE,
              data.numChannels,
              paFloat32,  /* 32 bit floating point output */
              NULL,
              SAMPLE_RATE,
              FRAMES_PER_BUFFER,  /* frames per buffer */
              0,    /* number of buffers, if zero then use default minimum */
              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;

    do
    {
        printf("Current amplitude = %f\n", data.amplitude );
        printf("Enter new amplitude or 'q' to quit.\n");
        fflush(stdout);
        gets( pad );
        if( pad[0] != 'q' )
        {
        // I tried to use atof but it seems to be broken on Mac OS X 10.1
            float amp;
            sscanf( pad, "%f", &amp );
            data.amplitude = amp;
        }
    } while( pad[0] != 'q' );

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

    Pa_CloseStream( stream );
    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;
}
コード例 #28
0
int main(void)
{
    PortAudioStream *stream;
    PaError err;
    paTestData data;
    int i;
    int timeout;
    
    printf("Play different tone sine waves that alternate between left and right channel.\n");
    printf("The low tone should be on the left channel.\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 = data.toggle = 0;
    data.countDown = SAMPLE_RATE;

    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 */
              NULL,
              Pa_GetDefaultOutputDeviceID(), /* default output device */
              2,          /* stereo output */
              paFloat32,      /* 32 bit floating point output */
              NULL,
              SAMPLE_RATE,
              FRAMES_PER_BUFFER,            /* frames per buffer */
              0,              /* number of buffers, if zero then use default minimum */
              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 several seconds.\n");
    timeout = NUM_SECONDS * 4;
    while( timeout > 0 )
    {
        Pa_Sleep( 300 );
        timeout -= 1;
    }

    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;
}
コード例 #29
0
ファイル: pa_dsound.c プロジェクト: svn2github/PortAudio
int Pa_CountDevices()
{
    if( sNumDevices <= 0 ) Pa_Initialize();
    return sNumDevices;
}
コード例 #30
0
ファイル: AudioPortAudio.cpp プロジェクト: BaraMGB/lmms
AudioPortAudio::setupWidget::setupWidget( QWidget * _parent ) :
	AudioDeviceSetupWidget( AudioPortAudio::name(), _parent )
{
	m_backend = new ComboBox( this, "BACKEND" );
	m_backend->setGeometry( 64, 15, 260, 20 );

	QLabel * backend_lbl = new QLabel( tr( "BACKEND" ), this );
	backend_lbl->setFont( pointSize<7>( backend_lbl->font() ) );
	backend_lbl->move( 8, 18 );

	m_device = new ComboBox( this, "DEVICE" );
	m_device->setGeometry( 64, 35, 260, 20 );

	QLabel * dev_lbl = new QLabel( tr( "DEVICE" ), this );
	dev_lbl->setFont( pointSize<7>( dev_lbl->font() ) );
	dev_lbl->move( 8, 38 );
	
/*	LcdSpinBoxModel * m = new LcdSpinBoxModel(  );
	m->setRange( DEFAULT_CHANNELS, SURROUND_CHANNELS );
	m->setStep( 2 );
	m->setValue( ConfigManager::inst()->value( "audioportaudio",
							"channels" ).toInt() );

	m_channels = new LcdSpinBox( 1, this );
	m_channels->setModel( m );
	m_channels->setLabel( tr( "CHANNELS" ) );
	m_channels->move( 308, 20 );*/

	// Setup models
	PaError err = Pa_Initialize();
	if( err != paNoError ) {
		printf( "Couldn't initialize PortAudio: %s\n", Pa_GetErrorText( err ) );
		return;
	}
	
	// todo: setup backend model
	const PaHostApiInfo * hi;
	for( int i = 0; i < Pa_GetHostApiCount(); ++i )
	{
		hi = Pa_GetHostApiInfo( i );
		m_setupUtil.m_backendModel.addItem( hi->name );
	}

	Pa_Terminate();


	const QString& backend = ConfigManager::inst()->value( "audioportaudio",
		"backend" );
	const QString& device = ConfigManager::inst()->value( "audioportaudio",
		"device" );
	
	int i = qMax( 0, m_setupUtil.m_backendModel.findText( backend ) );
	m_setupUtil.m_backendModel.setValue( i );
	
	m_setupUtil.updateDevices();
	
	i = qMax( 0, m_setupUtil.m_deviceModel.findText( device ) );
	m_setupUtil.m_deviceModel.setValue( i );

	connect( &m_setupUtil.m_backendModel, SIGNAL( dataChanged() ),
			&m_setupUtil, SLOT( updateDevices() ) );
			
	connect( &m_setupUtil.m_deviceModel, SIGNAL( dataChanged() ),
			&m_setupUtil, SLOT( updateChannels() ) );
			
	m_backend->setModel( &m_setupUtil.m_backendModel );
	m_device->setModel( &m_setupUtil.m_deviceModel );
}