• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ Pa_Initialize函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中Pa_Initialize函数的典型用法代码示例。如果您正苦于以下问题:C++ Pa_Initialize函数的具体用法?C++ Pa_Initialize怎么用?C++ Pa_Initialize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Pa_Initialize函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: AudioDevice

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,
//.........这里部分代码省略.........
开发者ID:BaraMGB,项目名称:lmms,代码行数:101,代码来源:AudioPortAudio.cpp


示例2: main

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 );
//.........这里部分代码省略.........
开发者ID:Ashura-X,项目名称:mame,代码行数:101,代码来源:paex_wmme_ac3.c


示例3: main

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;
}
开发者ID:svn2github,项目名称:PortAudio,代码行数:71,代码来源:patest_leftright.c


示例4: main

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

//.........这里部分代码省略.........
开发者ID:AmitShah,项目名称:quiet-lwip,代码行数:101,代码来源:kv_server.c


示例5: main

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;
}
开发者ID:sibosop,项目名称:smolek,代码行数:75,代码来源:pa_maxsines.cpp


示例6: pa_phone_setup

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();
    
//.........这里部分代码省略.........
开发者ID:petterreinholdtsen,项目名称:serval-dna,代码行数:101,代码来源:pa_phone.c


示例7: main

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;
}
开发者ID:Kirushanr,项目名称:audacity,代码行数:96,代码来源:debug_srate.c


示例8: Pa_Initialize

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;
}
开发者ID:nebogeo,项目名称:red-king,代码行数:67,代码来源:portaudio_client.cpp


示例9: initPlayerOutput

int initPlayerOutput() {
	PaError ret = Pa_Initialize();
	if(ret != paNoError)
		Py_FatalError("PortAudio init failed");
	return 0;
}
开发者ID:keverets,项目名称:music-player,代码行数:6,代码来源:ffmpeg_player_output.cpp


示例10: main

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;
}
开发者ID:dhull2,项目名称:squeezeslave,代码行数:99,代码来源:patest_sine.c


示例11: Pa_Initialize

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));
	}
}
开发者ID:crafn,项目名称:clover,代码行数:89,代码来源:audiodevice_pa.cpp


示例12: main

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;
}
开发者ID:CoolOppo,项目名称:audacity,代码行数:65,代码来源:debug_record_reuse.c


示例13: init_stuff

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");
}
开发者ID:srejv,项目名称:dspplayground,代码行数:86,代码来源:hellodelay.c


示例14: convertServerSampleRate

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();
}
开发者ID:Audifire,项目名称:mtasa-blue,代码行数:73,代码来源:CVoiceRecorder.cpp


示例15: main

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

//.........这里部分代码省略.........
开发者ID:jeffkaufman,项目名称:octaveless,代码行数:101,代码来源:octaveless.c


示例16: main

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ Pa_OpenStream函数代码示例发布时间:2022-05-30
下一篇:
C++ Pa_GetStreamInfo函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap