当前位置: 首页>>代码示例>>C++>>正文


C++ snd_pcm_open函数代码示例

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


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

示例1: set_pcm

int set_pcm()
{
    int    rc;
    int  dir = 0;
    int rate = 44100;;                /* ???? 44.1KHz*/
    int format = SND_PCM_FORMAT_S16_LE; /*     ???? 16      */
    int channels = 2;                 /*     ??? 2           */

    rc = snd_pcm_open(&handle, "default", SND_PCM_STREAM_PLAYBACK, 0);
    if (rc < 0)
    {
        perror("\nopen PCM device failed:");
        exit(1);
    }
    snd_pcm_hw_params_alloca(&params); //??params???

    rc = snd_pcm_hw_params_any(handle, params); //???params
    if (rc < 0)
    {
        perror("\nsnd_pcm_hw_params_any:");
        exit(1);
    }
    rc = snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);                               //???????
    if (rc < 0)
    {
        perror("\nsed_pcm_hw_set_access:");
        exit(1);

    }

    rc = snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_S16_LE);           //??16?????
    if (rc < 0)
    {
        perror("snd_pcm_hw_params_set_format failed:");
        exit(1);
    }

    rc = snd_pcm_hw_params_set_channels(handle, params, channels); //????,1????>??2?????
    if (rc < 0)
    {
        perror("\nsnd_pcm_hw_params_set_channels:");
        exit(1);
    }

    rc = snd_pcm_hw_params_set_rate_near(handle, params, &rate, &dir); //??>??
    if (rc < 0)
    {
        perror("\nsnd_pcm_hw_params_set_rate_near:");
        exit(1);
    }


    rc = snd_pcm_hw_params(handle, params);
    if (rc < 0)
    {
        perror("\nsnd_pcm_hw_params: ");
        exit(1);
    }

    return 0;
}
开发者ID:SilunWang,项目名称:xv6,代码行数:61,代码来源:mp3player.c

示例2: alsa_open_audio

    /* return 0 on success */
int alsa_open_audio(int naudioindev, int *audioindev, int nchindev,
    int *chindev, int naudiooutdev, int *audiooutdev, int nchoutdev,
    int *choutdev, int rate, int blocksize)
{
    int err, inchans = 0, outchans = 0, subunitdir;
    char devname[512];
    snd_output_t* out;
    int frag_size = (blocksize ? blocksize : ALSA_DEFFRAGSIZE);
    int nfrags, i, iodev, dev2;
    int wantinchans, wantoutchans, device;

    nfrags = sys_schedadvance * (float)rate / (1e6 * frag_size);
        /* save our belief as to ALSA's buffer size for later */
    alsa_buf_samps = nfrags * frag_size;
    alsa_nindev = alsa_noutdev = 0;
    alsa_jittermax = ALSA_DEFJITTERMAX;

    if (sys_verbose)
        post("audio buffer set to %d", (int)(0.001 * sys_schedadvance));

    for (iodev = 0; iodev < naudioindev; iodev++)
    {
        alsa_numbertoname(audioindev[iodev], devname, 512);
        err = snd_pcm_open(&alsa_indev[alsa_nindev].a_handle, devname,
            SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK);
        check_error(err, 0, "snd_pcm_open");
        if (err < 0)
            continue;
        alsa_indev[alsa_nindev].a_devno = audioindev[iodev];
        snd_pcm_nonblock(alsa_indev[alsa_nindev].a_handle, 1);
        if (sys_verbose)
            post("opened input device name %s", devname);
        alsa_nindev++;
    }
    for (iodev = 0; iodev < naudiooutdev; iodev++)
    {
        alsa_numbertoname(audiooutdev[iodev], devname, 512);
        err = snd_pcm_open(&alsa_outdev[alsa_noutdev].a_handle, devname,
            SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
        check_error(err, 1, "snd_pcm_open");
        if (err < 0)
            continue;
        alsa_outdev[alsa_noutdev].a_devno = audiooutdev[iodev];
        snd_pcm_nonblock(alsa_outdev[alsa_noutdev].a_handle, 1);
        alsa_noutdev++;
    }
    if (!alsa_nindev && !alsa_noutdev)
        goto blewit;

        /* If all the open devices support mmap_noninterleaved, let's call
        Wini's code in s_audio_alsamm.c */
    alsa_usemmap = 1;
    for (iodev = 0; iodev < alsa_nindev; iodev++)
        if (!alsaio_canmmap(&alsa_indev[iodev]))
            alsa_usemmap = 0;
    for (iodev = 0; iodev < alsa_noutdev; iodev++)
        if (!alsaio_canmmap(&alsa_outdev[iodev]))
            alsa_usemmap = 0;
    if (alsa_usemmap)
    {
        post("using mmap audio interface");
        if (alsamm_open_audio(rate, blocksize))
            goto blewit;
        else return (0);
    }
    for (iodev = 0; iodev < alsa_nindev; iodev++)
    {
        int channels = chindev[iodev];
        if (alsaio_setup(&alsa_indev[iodev], 0, &channels, &rate,
            nfrags, frag_size) < 0)
                goto blewit;
        inchans += channels;
    }
    for (iodev = 0; iodev < alsa_noutdev; iodev++)
    {
        int channels = choutdev[iodev];
        if (alsaio_setup(&alsa_outdev[iodev], 1, &channels, &rate,
            nfrags, frag_size) < 0)
                goto blewit;
        outchans += channels;
    }
    if (!inchans && !outchans)
        goto blewit;

    for (iodev = 0; iodev < alsa_nindev; iodev++)
        snd_pcm_prepare(alsa_indev[iodev].a_handle);
    for (iodev = 0; iodev < alsa_noutdev; iodev++)
        snd_pcm_prepare(alsa_outdev[iodev].a_handle);

        /* if duplex we can link the channels so they start together */
    for (iodev = 0; iodev < alsa_nindev; iodev++)
        for (dev2 = 0; dev2 < alsa_noutdev; dev2++)
    {
        if (alsa_indev[iodev].a_devno == alsa_outdev[iodev].a_devno)
        {
            snd_pcm_link(alsa_indev[iodev].a_handle,
                alsa_outdev[iodev].a_handle);
        }
    }
//.........这里部分代码省略.........
开发者ID:avilleret,项目名称:pure-data,代码行数:101,代码来源:s_audio_alsa.c

示例3: alsa_audio_reconfig

static int
alsa_audio_reconfig(audio_decoder_t *ad)
{
  decoder_t *d = (decoder_t *)ad;
  snd_pcm_t *h;
  int r;

  alsa_audio_fini(ad);

  if(d->h != NULL) {
    snd_pcm_close(d->h);
    d->h = NULL;
    TRACE(TRACE_DEBUG, "ALSA", "Closing device");
  }

  const char *dev = alsa_get_devicename();

  if((r = snd_pcm_open(&h, dev, SND_PCM_STREAM_PLAYBACK, 0) < 0)) {
    TRACE(TRACE_ERROR, "ALSA", "Unable to open %s -- %s", 
	  dev, snd_strerror(r));
    return -1;
  }

  r = snd_pcm_set_params(h, SND_PCM_FORMAT_S16, SND_PCM_ACCESS_RW_INTERLEAVED,
			 2, 48000, 0, 100000);

  if(r < 0) {
    TRACE(TRACE_ERROR, "ALSA", "Unable to set params on %s -- %s", 
	  dev, snd_strerror(r));
    return -1;
  }

  snd_pcm_hw_params_t *hwp;
  snd_pcm_hw_params_alloca(&hwp);

  snd_pcm_hw_params_current(h, hwp);

  unsigned int val;
  snd_pcm_uframes_t psize, bsize;

  snd_pcm_hw_params_get_rate(hwp, &val, 0);
  ad->ad_out_sample_rate = val;

  snd_pcm_hw_params_get_period_size(hwp, &psize, 0);
  ad->ad_tile_size = psize * 2;

  snd_pcm_hw_params_get_buffer_size(hwp, &bsize);
  d->max_frames_per_write = bsize;
  
  TRACE(TRACE_DEBUG, "ALSA", "Opened %s", dev);

  ad->ad_out_sample_format = AV_SAMPLE_FMT_S16;
  ad->ad_out_sample_rate = 48000;
  ad->ad_out_channel_layout = AV_CH_LAYOUT_STEREO;
  d->h = h;

  snd_pcm_prepare(d->h);
  

  int channels = 2;
  d->tmp = malloc(sizeof(uint16_t) * channels * d->max_frames_per_write);

  return 0;
}
开发者ID:copernic-us,项目名称:showtime-1,代码行数:64,代码来源:alsa.c

示例4: playback

void playback() {

    int err;
    unsigned int i;
    snd_pcm_t *handle;

//    for (i = 0; i < sizeof(buffer); i++)
//            buffer[i] = random() & 0xff;
    if ((err = snd_pcm_open(&handle, "default", SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
            printf("Playback open error: %s\n", snd_strerror(err));
            exit(EXIT_FAILURE);
    }

    initialize(handle);

	  printBuffer(buffer, 0, 10);
//	    for (i = 0; i < sizeof(buffer); i++)
//	    	buffer[i] = random() & 0xff;
	for (i = 0; i < NUM_FRAMES; i++) {
		if ((err = snd_pcm_writei (handle, buffer+FRAME_SIZE*i*mult, FRAME_SIZE)) != FRAME_SIZE) {
		  fprintf (stderr, "write from audio interface failed (%s)\n",
				   err, snd_strerror (err));
		  exit (1);
		}
		fprintf(stdout, "write %d done\n", i);
		printBuffer(buffer, FRAME_SIZE*i*mult, 10);
	}
    snd_pcm_close(handle);

//    int err;
//           unsigned int i;
//           snd_pcm_t *handle;
//           snd_pcm_sframes_t frames;
//           for (i = 0; i < sizeof(buffer); i++)
//                   buffer[i] = random() & 0xff;
//           if ((err = snd_pcm_open(&handle, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
//                   printf("Playback open error: %s\n", snd_strerror(err));
//                   exit(EXIT_FAILURE);
//           }
//           if ((err = snd_pcm_set_params(handle,
//                                         SND_PCM_FORMAT_U8,
//                                         SND_PCM_ACCESS_RW_INTERLEAVED,
//                                         1,
//                                         48000,
//                                         1,
//                                         500000)) < 0) {   /* 0.5sec */
//                   printf("Playback open error: %s\n", snd_strerror(err));
//                   exit(EXIT_FAILURE);
//           }
//           for (i = 0; i < 16; i++) {
//                   frames = snd_pcm_writei(handle, buffer, sizeof(buffer));
//                   if (frames < 0)
//                           frames = snd_pcm_recover(handle, frames, 0);
//                   if (frames < 0) {
//                           printf("snd_pcm_writei failed: %s\n", snd_strerror(frames));
//                           break;
//                   }
//                   if (frames > 0 && frames < (long)sizeof(buffer))
//                           printf("Short write (expected %li, wrote %li)\n", (long)sizeof(buffer), frames);
//           }
//           snd_pcm_close(handle);
}
开发者ID:gforth,项目名称:AlsaRecorder,代码行数:62,代码来源:capture_and_playback.c

示例5: alsa_play_hw

int alsa_play_hw(alsa_play_t alsa_play, glc_audio_format_message_t *fmt_msg)
{
	snd_pcm_hw_params_t *hw_params = NULL;
	snd_pcm_access_t access;
	unsigned int period_time;
	unsigned int buffer_time;
	int dir = 0, ret = 0;

	if (unlikely(fmt_msg->id != alsa_play->id))
		return 0;

	alsa_play->flags    = fmt_msg->flags;
	alsa_play->format   = fmt_msg->format;
	alsa_play->rate     = fmt_msg->rate;
	alsa_play->channels = fmt_msg->channels;

	if (alsa_play->pcm) /* re-open */
		snd_pcm_close(alsa_play->pcm);

	if (alsa_play->flags & GLC_AUDIO_INTERLEAVED)
		access = SND_PCM_ACCESS_RW_INTERLEAVED;
	else
		access = SND_PCM_ACCESS_RW_NONINTERLEAVED;

	if (unlikely((ret = snd_pcm_open(&alsa_play->pcm, alsa_play->device,
				SND_PCM_STREAM_PLAYBACK, 0)) < 0))
		goto err;
	snd_pcm_hw_params_alloca(&hw_params);
	if (unlikely((ret = snd_pcm_hw_params_any(alsa_play->pcm, hw_params)) < 0))
		goto err;
	if (unlikely((ret = snd_pcm_hw_params_set_access(alsa_play->pcm,
						hw_params, access)) < 0))
		goto err;
	if (unlikely((ret = snd_pcm_hw_params_set_format(alsa_play->pcm, hw_params,
						glc_fmt_to_pcm_fmt(alsa_play->format))) < 0))
		goto err;
	if (unlikely((ret = snd_pcm_hw_params_set_channels(alsa_play->pcm, hw_params,
						  alsa_play->channels)) < 0))
		goto err;
	if (unlikely((ret = snd_pcm_hw_params_set_rate(alsa_play->pcm, hw_params,
					      alsa_play->rate, 0)) < 0))
		goto err;

	if (unlikely((ret = snd_pcm_hw_params_get_buffer_time_max(hw_params,
						&buffer_time, 0))))
		goto err;

	if (buffer_time > 1000000) {
		glc_log(alsa_play->glc, GLC_INFO, "alsa_play",
			"buffer time max is %u usec. We will limit it to 1 sec",
			buffer_time);
		buffer_time = 1000000;
	}

	period_time = buffer_time / 4;
	alsa_play->silence_threshold = period_time*2000;

	if (unlikely((ret = snd_pcm_hw_params_set_period_time_near(alsa_play->pcm,
		hw_params, &period_time, 0)) < 0))
		goto err;

	if (unlikely((ret = snd_pcm_hw_params_set_buffer_time_near(alsa_play->pcm,
		hw_params, &buffer_time, 0)) < 0))
		goto err;
	if (unlikely((ret = snd_pcm_hw_params(alsa_play->pcm, hw_params)) < 0))
		goto err;

	alsa_play->bufs = (void **) malloc(sizeof(void *) * alsa_play->channels);

	glc_log(alsa_play->glc, GLC_INFO, "alsa_play",
		"opened pcm %s for playback. buffer_time: %u",
		alsa_play->device, buffer_time);

	return 0;
err:
	glc_log(alsa_play->glc, GLC_ERROR, "alsa_play",
		"can't initialize pcm %s: %s (%d)",
		alsa_play->device, snd_strerror(ret), ret);
	return -ret;
}
开发者ID:prodigeni,项目名称:glcs,代码行数:80,代码来源:alsa_play.c

示例6: snd_pcm_close

/**
* @brief Setup the ALSA handle to the audio device
*/
void AlsaPlayback::setupHandle()
{
	if(alsa_handle)
	{
		snd_pcm_close(alsa_handle);
		alsa_handle = NULL;
	}

	if(snd_pcm_open(&alsa_handle, "default", SND_PCM_STREAM_PLAYBACK, 0) < 0)
	{
		TRACE("Unable to open playback device!!\n");
		alsa_handle = NULL;
	}
	else
	{
		int rc = -1;
		snd_pcm_hw_params_t *params = NULL;

		/* Allocate a hardware parameters object. */
		snd_pcm_hw_params_malloc(&params);

		if(NULL != params)
		{
			int dir = 0;

			/* Fill it in with default values. */
			snd_pcm_hw_params_any(alsa_handle, params);

			/* Set the desired hardware parameters. */
			/* Interleaved mode */
			snd_pcm_hw_params_set_access(alsa_handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);

			/* Signed 16-bit little-endian format */
			snd_pcm_hw_params_set_format(alsa_handle, params, SND_PCM_FORMAT_S16_LE);

			/* One channel (mono) */
			snd_pcm_hw_params_set_channels(alsa_handle, params, 1);

			/* set sampling rate */
			snd_pcm_hw_params_set_rate_near(alsa_handle, params, &AlsaPlayback::_sample_rate, &dir);

			/* Set period size to 128 frames (samples) */
			frames = AlsaPlayback::FRAME_PERIOD;
			snd_pcm_hw_params_set_period_size_near(alsa_handle, params, &frames, &dir);

			snd_pcm_uframes_t buf_size = MINIMUM_SAMPLE_SET_SIZE;
			snd_pcm_hw_params_set_buffer_size_near(alsa_handle, params, &buf_size);

			/* Write the parameters to the driver */
			rc = snd_pcm_hw_params(alsa_handle, params);

			if(rc >= 0)
			{
				TRACE("AlsaPlayback init completed successfully..\n");
			}
			else
			{
				snd_pcm_close(alsa_handle);
				alsa_handle = NULL;
				TRACE("AlsaPlayback init failed\n");
			}

			snd_pcm_hw_params_free(params);
			params = NULL;
		}
		else
		{
			TRACE("playAudio - snd_pcm_hw_params_alloc() failed\n");
		}
	}
}
开发者ID:AnXi-TieGuanYin-Tea,项目名称:Multi-Channel-Audio-Mixer,代码行数:74,代码来源:AlsaAudioPlayback.cpp

示例7: init_alsa

int init_alsa(unsigned int channels, unsigned sample_rate,
				 snd_pcm_format_t format)
{
	int	ret;
	snd_pcm_hw_params_t *hw_params;

	playback_handle = NULL;
	ret = snd_pcm_open(&playback_handle, "default", SND_PCM_STREAM_PLAYBACK,
			0);
	if (ret < 0) {
		fprintf(stderr, "can NOT open soundcard\n");
		goto fail;
	}

	ret = snd_pcm_hw_params_malloc(&hw_params);
	if (ret < 0) {
		fprintf(stderr, "can NOT allocate hardware paramter structure (%s)\n",
				snd_strerror(ret));
		goto fail;
	}

	ret = snd_pcm_hw_params_any(playback_handle, hw_params);
	if (ret < 0) {
		fprintf(stderr, "can NOT initialize hardware paramter structure (%s)\n",
				snd_strerror(ret));
		goto fail;
	}

	ret = snd_pcm_hw_params_set_access(playback_handle, hw_params,
									   SND_PCM_ACCESS_RW_INTERLEAVED);
	if (ret < 0) {
		fprintf(stderr, "can NOT set access type (%s)\n", snd_strerror(ret));
		goto fail;
	}

	ret = snd_pcm_hw_params_set_format(playback_handle, hw_params, format);
	if (ret < 0) {
		fprintf(stderr, "can NOT set sample format (%s)\n", snd_strerror(ret));
		goto fail;
	}

	ret = snd_pcm_hw_params_set_rate_near(playback_handle, hw_params,
										  &sample_rate, 0);
	if (ret < 0) {
		fprintf(stderr, "can NOT set sample rate (%s)\n", snd_strerror(ret));
		goto fail;
	}

	ret = snd_pcm_hw_params_set_channels(playback_handle, hw_params, channels);
	if (ret < 0) {
		fprintf(stderr, "can NOT set channels (%s)\n", snd_strerror(ret));
		goto fail;
	}

	snd_pcm_hw_params_get_buffer_size_max(hw_params, &buffer_size);
	buffer_size = buffer_size < ALSA_BUFFER_SIZE_MAX ?
				  buffer_size : ALSA_BUFFER_SIZE_MAX;
	ret = snd_pcm_hw_params_set_buffer_size_near(playback_handle, hw_params,
												 &buffer_size);
	if (ret < 0) {
		fprintf(stderr, "can NOT set alsa buffer size (%s)\n", snd_strerror(ret));
		goto fail;
	}

	snd_pcm_hw_params_get_period_size_min(hw_params, &period_size, NULL);
	if (!period_size)
		period_size = buffer_size / 4;
	ret = snd_pcm_hw_params_set_period_size_near(playback_handle, hw_params,
												 &period_size, NULL);
	if (ret < 0) {
		fprintf(stderr, "can NOT set alsa period size (%s)\n", snd_strerror(ret));
		goto fail;
	}

	ret = snd_pcm_hw_params(playback_handle, hw_params);
	if (ret < 0) {
		fprintf(stderr, "can NOT set parameters (%s)\n", snd_strerror(ret));
		goto fail;
	}
	
	snd_pcm_hw_params_free(hw_params);

	audio_channels = channels;
	audio_sample_rate = sample_rate;
	audio_format = format;

	ret = 0;

	return ret;
fail:
	if (playback_handle) {
		snd_pcm_close(playback_handle);
		playback_handle = NULL;
	}
	return ret;
}
开发者ID:fedoracdu,项目名称:tyl_player,代码行数:96,代码来源:alsa.c

示例8: Init

bool CASDeviceAlsa::Init( const char *pcDev, bool bIsOutput )
{
    int iErr;

    if( ( iErr = snd_pcm_open( &m_poHandle, pcDev, ( bIsOutput ? SND_PCM_STREAM_PLAYBACK : SND_PCM_STREAM_CAPTURE ), 0 ) ) < 0 )
        AS_ERROR_RET( "cannot open audio device %s (%s)\n", pcDev, snd_strerror( iErr ) );

    if( ( iErr = snd_pcm_hw_params_malloc( &m_poHW ) ) < 0 )
        AS_ERROR_RET( "cannot allocate hardware parameter structure (%s)\n", snd_strerror( iErr ) );

    if( ( iErr = snd_pcm_hw_params_any( m_poHandle, m_poHW ) ) < 0 )
        AS_ERROR_RET( "cannot initialize hardware parameter structure (%s)\n", snd_strerror( iErr ) );

    if( ( iErr = snd_pcm_hw_params_set_access( m_poHandle, m_poHW, SND_PCM_ACCESS_RW_INTERLEAVED ) ) < 0 )
        AS_ERROR_RET( "cannot set access type (%s)\n", snd_strerror( iErr ) );

    if( ( iErr = snd_pcm_hw_params_set_format( m_poHandle, m_poHW, SND_PCM_FORMAT_S16_LE ) ) < 0 )
        AS_ERROR_RET( "cannot set sample format (%s)\n", snd_strerror( iErr ) );

    unsigned int uiSF = m_uiSampleFreq;
    if( ( iErr = snd_pcm_hw_params_set_rate_near( m_poHandle, m_poHW, &uiSF, 0 ) ) < 0 )
        AS_ERROR_RET( "cannot set sample rate (%s)\n", snd_strerror( iErr ) );
    if( uiSF != m_uiSampleFreq ) {
        fprintf(stderr, "cannot set requested sample rate, asked for %d got %d\n", m_uiSampleFreq, uiSF );
        m_uiSampleFreq = uiSF;
    }

    if( ( iErr = snd_pcm_hw_params_set_channels( m_poHandle, m_poHW, 2 ) ) < 0 )
        AS_ERROR_RET( "cannot set channel count (%s)\n", snd_strerror( iErr ) );

    /*
    m_uiFragments = 2;
    // http://www.bel.fi/~alankila/blog/2005/08/21/Full%20Duplex%20ALSA.html
    //if( ( iErr = snd_pcm_hw_params_set_periods( m_poHandle, m_poHW, 2, 0 ) ) < 0 )
    if( ( iErr = snd_pcm_hw_params_set_periods_near( m_poHandle, m_poHW, &m_uiFragments, 0 ) ) < 0 )
    	AS_ERROR_RET( "cannot periods (%s)\n", snd_strerror( iErr ) );
    */

    // ??
    //if( ( iErr = snd_pcm_hw_params_set_period_size( m_poHandle, m_poHW, m_uliBufferSamples, 0 ) ) < 0 )
    //	AS_ERROR_RET( "cannot set period size (%s)\n", snd_strerror( iErr ) );
    snd_pcm_uframes_t oBS = m_uiBufferSamples;

    /*
    //unsigned int uiFrameSize = m_uiChannels * ( m_uiSampleDepth / 8 );
    unsigned int uiFrag = oBS % m_uiFragments;
    if( uiFrag )
    {
    	oBS += m_uiFragments - uiFrag;
    }
    */

    //printf( "> frames: %li\n", oBS );
    if( ( iErr = snd_pcm_hw_params_set_buffer_size_near( m_poHandle, m_poHW, &oBS ) ) < 0 )
        AS_ERROR_RET( "cannot set buffer size (%s)\n", snd_strerror( iErr ) );
    if( oBS != m_uiBufferSamples )
    {
        fprintf(stderr, "Could not set requested buffer size, asked for %d got %li\n", m_uiBufferSamples, oBS );
        m_uiBufferSamples = oBS;
    }

    /*
    unsigned int frame_size = m_uiChannels * (m_uiSampleDepth / 8);
    snd_pcm_uframes_t frames = m_uiBufferSamples / frame_size * m_uiFragments;
    printf( "> frames: %li\n", frames );

    if ((iErr = snd_pcm_hw_params_set_buffer_size_near(m_poHandle, m_poHW, &frames)) < 0) {
    	AS_ERROR_RET( "Error setting buffer_size %li frames: %s\n", frames,
    	snd_strerror(iErr));
    return 1;
    }
    if (m_uiBufferSamples != frames * frame_size / m_uiFragments) {
    	AS_ERROR_RET( "Could not set requested buffer size, asked for %d got %li\n", m_uiBufferSamples, frames * frame_size / m_uiFragments);
    m_uiBufferSamples = frames * frame_size / m_uiFragments;
    }
    */

    if( ( iErr = snd_pcm_hw_params( m_poHandle, m_poHW ) ) < 0 )
        AS_ERROR_RET( "cannot set parameters (%s)\n", snd_strerror( iErr ) );

    CreateBuffer();

    if( !bIsOutput )
        return true;

    // tell ALSA to wake us up whenever m_sliBufferSize or more frames
    // of playback data can be delivered. Also, tell
    // ALSA that we'll start the device ourselves.

    if( ( iErr = snd_pcm_sw_params_malloc( &m_poSW ) ) < 0 )
        AS_ERROR_RET( "cannot allocate software parameters structure (%s)\n", snd_strerror( iErr ));

    if( ( iErr = snd_pcm_sw_params_current( m_poHandle, m_poSW ) ) < 0 )
        AS_ERROR_RET( "cannot initialize software parameters structure (%s)\n", snd_strerror( iErr ));

    // doesn't work when recording!
    //if( ( iErr = snd_pcm_sw_params_set_avail_min( m_poHandle, poParamSW, m_sliBufferSize ) ) < 0 )
    //	AS_ERROR_RET( "cannot set minimum available count (%s)\n", snd_strerror( iErr ) );

    if( ( iErr = snd_pcm_sw_params_set_start_threshold( m_poHandle, m_poSW, 0U ) ) < 0 )
//.........这里部分代码省略.........
开发者ID:0rel,项目名称:okkuplektor,代码行数:101,代码来源:AS.cpp

示例9: init_alsa

void init_alsa() {
//  long loops; //number of periods
  int rc;	//for error check
  int size;	//size of 1 period in
  snd_pcm_t *handle;
  snd_pcm_hw_params_t *params;
  unsigned int val;
  int dir;
  snd_pcm_uframes_t frames;
//  char *buffer;

  /* Open PCM device for playback. */
  rc = snd_pcm_open(&handle, "default",
                    SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC |SND_PCM_NONBLOCK);
  if (rc < 0) {
    fprintf(stderr,
            "unable to open pcm device: %s\n",
            snd_strerror(rc));
    exit(1);
  }
  handlec=handle;
  /* Allocate a hardware parameters object. */
  snd_pcm_hw_params_alloca(&params);

  /* Fill it in with default values. */
  snd_pcm_hw_params_any(handle, params);

  /* Set the desired hardware parameters. */

  /* Interleaved mode */
  snd_pcm_hw_params_set_access(handle, params,
                      SND_PCM_ACCESS_RW_INTERLEAVED);

  /* Signed 16-bit little-endian format */
  assert((snd_pcm_hw_params_set_format(handle, params,
                              SND_PCM_FORMAT_S16_LE))==0);

  /* Two channels (stereo) */
  snd_pcm_hw_params_set_channels(handle, params, 2);

  /* 44100 bits/second sampling rate (CD quality) */
  val = 44100;
  snd_pcm_hw_params_set_rate_near(handle, params,
                                  &val, &dir);

  /* Set period size to 32 frames. */
  frames = 32;
  snd_pcm_hw_params_set_period_size_near(handle,
                              params, &frames, &dir);

  /* Write the parameters to the driver */
  rc = snd_pcm_hw_params(handle, params);
  if (rc < 0) {
    fprintf(stderr,
            "unable to set hw parameters: %s\n",
            snd_strerror(rc));
    exit(1);
  }

  /* Use a buffer large enough to hold one period */
  snd_pcm_hw_params_get_period_size(params, &frames,
                                    &dir);
  fprintf(stderr,"Period framesize:%ld\n",(long)frames);
  //printf("Period dir:%ld\n",(long)dir);
  size = frames * 4; /* 2 bytes/sample, 2 channels */

  /* We want to loop for 5 seconds */
  snd_pcm_hw_params_get_period_time(params,
                                    &val, &dir);
  /* 5 seconds in microseconds divided by
   * period time */
   
//==================================================================================
	init_buffers();
//	char c1, c2;
//	int range, freq;
//	initscr();
//	noecho();
//	raw();
//		do {
/*			c1 = getch();
			clear();
			if(c1=='q'||c1=='w'||c1=='e'||c1=='r'||c1=='t'||c1=='y'||c1=='u'||c1=='i') 
			{
				switch(c1) {
					case 'q': range = 1;
							break;
					case 'w': range = 2;
							break;
					case 'e': range = 4;
							break;
					case 'r': range = 8;
							break;
					case 't': range = 16;
							break;
					case 'y': range = 32;
							break;
					case 'u': range = 64;
							break;
					case 'i': range = 128;
//.........这里部分代码省略.........
开发者ID:vmiheer,项目名称:audics,代码行数:101,代码来源:testn.c

示例10: drvHostALSAAudioOpen

static int drvHostALSAAudioOpen(bool fIn,
                                PALSAAUDIOSTREAMCFG pCfgReq,
                                PALSAAUDIOSTREAMCFG pCfgObt,
                                snd_pcm_t **pphPCM)
{
    snd_pcm_t *phPCM = NULL;
    int rc;

    unsigned int cChannels = pCfgReq->nchannels;
    unsigned int uFreq = pCfgReq->freq;
    snd_pcm_uframes_t obt_buffer_size;

    do
    {
        const char *pszDev = fIn ? s_ALSAConf.pcm_name_in : s_ALSAConf.pcm_name_out;
        if (!pszDev)
        {
            LogRel(("ALSA: Invalid or no %s device name set\n",
                    fIn ? "input" : "output"));
            rc = VERR_INVALID_PARAMETER;
            break;
        }

        int err = snd_pcm_open(&phPCM, pszDev,
                               fIn ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
                               SND_PCM_NONBLOCK);
        if (err < 0)
        {
            LogRel(("ALSA: Failed to open \"%s\" as %s: %s\n", pszDev,
                    fIn ? "ADC" : "DAC", snd_strerror(err)));
            rc = VERR_GENERAL_FAILURE; /** @todo Find a better rc. */
            break;
        }

        snd_pcm_hw_params_t *pHWParms;
        snd_pcm_hw_params_alloca(&pHWParms); /** @todo Check for successful allocation? */
        err = snd_pcm_hw_params_any(phPCM, pHWParms);
        if (err < 0)
        {
            LogRel(("ALSA: Failed to initialize hardware parameters: %s\n",
                    snd_strerror(err)));
            rc = VERR_GENERAL_FAILURE; /** @todo Find a better rc. */
            break;
        }

        err = snd_pcm_hw_params_set_access(phPCM, pHWParms,
                                           SND_PCM_ACCESS_RW_INTERLEAVED);
        if (err < 0)
        {
            LogRel(("ALSA: Failed to set access type: %s\n", snd_strerror(err)));
            rc = VERR_GENERAL_FAILURE; /** @todo Find a better rc. */
            break;
        }

        err = snd_pcm_hw_params_set_format(phPCM, pHWParms, pCfgReq->fmt);
        if (err < 0)
        {
            LogRel(("ALSA: Failed to set audio format to %d: %s\n",
                    pCfgReq->fmt, snd_strerror(err)));
            rc = VERR_GENERAL_FAILURE; /** @todo Find a better rc. */
            break;
        }

        err = snd_pcm_hw_params_set_rate_near(phPCM, pHWParms, &uFreq, 0);
        if (err < 0)
        {
            LogRel(("ALSA: Failed to set frequency to %dHz: %s\n",
                    pCfgReq->freq, snd_strerror(err)));
            rc = VERR_GENERAL_FAILURE; /** @todo Find a better rc. */
            break;
        }

        err = snd_pcm_hw_params_set_channels_near(phPCM, pHWParms, &cChannels);
        if (err < 0)
        {
            LogRel(("ALSA: Failed to set number of channels to %d\n", pCfgReq->nchannels));
            rc = VERR_GENERAL_FAILURE; /** @todo Find a better rc. */
            break;
        }

        if (   cChannels != 1
            && cChannels != 2)
        {
            LogRel(("ALSA: Number of audio channels (%u) not supported\n", cChannels));
            rc = VERR_GENERAL_FAILURE; /** @todo Find a better rc. */
            break;
        }

        unsigned int period_size = pCfgReq->period_size;
        unsigned int buffer_size = pCfgReq->buffer_size;

        if (   !((fIn && s_ALSAConf.size_in_usec_in)
            ||  (!fIn && s_ALSAConf.size_in_usec_out)))
        {
            if (!buffer_size)
            {
                buffer_size = DEFAULT_BUFFER_SIZE;
                period_size = DEFAULT_PERIOD_SIZE;
            }
        }
//.........这里部分代码省略.........
开发者ID:zBMNForks,项目名称:virtualbox-org-svn-vbox-trunk,代码行数:101,代码来源:DrvHostALSAAudio.cpp

示例11: main

main(int argc, char *argv[])
{ 

  FILE *fp;
  int fd,arg;
  snd_pcm_t *handle;
  snd_pcm_hw_params_t *hw_params;
  int rate=8000;
  float f[WINDOW],hann[WINDOW],w[WINDOW],w2[WINDOW],s0,s1=0,tot;
  float ac[ORDER+1],lcp[ORDER+1],lsp[ORDER],l[ORDER],weight[ORDER],delta,d;
  short sample,s[160],buf[2000];
  int i,j,n,b,toggle=1;
  float e,laste=0;
  int ebit=ETOPBIT, ebuff=0;
  int sound=0; // boolean start/stop
  float f2[FFT],min;
  float real[FFT],imag[FFT];
  int dummy[100000];
  float amp[WINDOW],pha[WINDOW];
  int frame=0;
  SpeexPreprocessState *st;
 
  for (i=0; i<8; i++) report[i]=0; 
  st = speex_preprocess_state_init(160, 8000);
  i=1;
  speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_DENOISE, &i);
//  i=1;
//  speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_DEREVERB, &i);
//  e=.0;
//  speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_DEREVERB_DECAY, &e);
//  e=.0;
//  speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_DEREVERB_LEVEL, &e);
  
  
  setup_twiddles(realtwiddle,imtwiddle,FFT);
  
  for (i=0; i<WINDOW; i++) f[i]=0;
  for (i=0; i<ORDER; i++) {last[i]=0; last2[i]=0;}
  
  for(i=0; i<WINDOW; i++) hann[i]=0.5-0.5*cos(2.0*M_PI*i/(WINDOW-1));
  
  if (argc==2) training=atoi(argv[1]);
  fprintf(stderr,"training=%i\n",training); //  exit(0);
  
  cbsize=0; start[0]=0; size[0]=0;
  if (training==0) if (fp=fopen("cb.txt","r")) {
    while(!feof(fp)) {
      fscanf(fp,"%i\n",&size[cbsize]);
      for (i=start[cbsize]; i<start[cbsize]+size[cbsize]; i++) {
        for (n=1; n<FF2-1; n++) fscanf(fp,"%f,",&cb[i][n]); fscanf(fp,"\n");
      }
      start[cbsize+1]=start[cbsize]+size[cbsize];  cbsize++; 
    }
    fclose(fp);
  }
  //for (i=0; i<cbsize; i++) printf("%i,\n",size[i]); exit(0);
  
  //---------------------------------
  
  
  fp=fopen("/tmp/b.raw","w");
  snd_pcm_open(&handle, "default", SND_PCM_STREAM_CAPTURE, 0);	
  snd_pcm_hw_params_malloc(&hw_params);			 
  snd_pcm_hw_params_any(handle, hw_params);
  snd_pcm_hw_params_set_access(handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);	
  snd_pcm_hw_params_set_format(handle, hw_params, SND_PCM_FORMAT_S16_LE);	
  snd_pcm_hw_params_set_rate_near(handle, hw_params, &rate, 0);
  snd_pcm_hw_params_set_channels(handle, hw_params, 2);
  snd_pcm_hw_params(handle, hw_params);
  snd_pcm_hw_params_free(hw_params);
  snd_pcm_prepare(handle);
  
  //printf("sleep 1...\n"); sleep(1); printf("OK, go....\n");
  while(1) {
    for (i=0; i<WINDOW-STEP; i++) f[i]=f[i+STEP]; // shift samples down
    if (toggle) {
      //read(fd,s,160*2);
      snd_pcm_readi(handle, buf, 160);
      for (i=0; i<160; i++) s[i]=buf[i*2];
      speex_preprocess_run(st, s);
    }
    else bcopy(&s[80],s,80*2);
    toggle=!toggle;
    for (i=WINDOW-STEP,j=0; i<WINDOW; i++,j++) {
      sample=s[j]; s0=(float)sample;
      f[i]=s0-s1*EMPH; s1=s0; // 1.0 pre-emphasis
      fwrite(&sample,2,1,fp);
  
    }
    for (i=0; i<WINDOW; i++) w[i]=f[i];
    // remove any DC level....
    tot=0; for (i=0; i<WINDOW; i++) tot+=w[i]; tot/=WINDOW;
    for (i=0; i<WINDOW; i++) w[i]-=tot;
    
    for (i=0; i<WINDOW; i++) w[i]*=hann[i]; // window data
 
    autocorrelate(w,ac,WINDOW,ORDER);
    wld(&lpc[1],ac,ORDER); lpc[0]=1.0;
        // e=ac[0];
    e=0;for(i=0; i<=ORDER; i++) e+=ac[i]*lpc[i];   if (e<0) e=0;
//.........这里部分代码省略.........
开发者ID:briansm-github,项目名称:chip_voicekeyboard_offline,代码行数:101,代码来源:go.c

示例12: FreeStream

bool PAPlayer::CreateStream(int num, int channels, int samplerate, int bitspersample, CStdString codec)
{
  snd_pcm_hw_params_t *hw_params=NULL;

  FreeStream(num);

  m_packet[num][0].packet = (BYTE*)malloc(PACKET_SIZE * PACKET_COUNT);
  for (int i = 1; i < PACKET_COUNT ; i++)
    m_packet[num][i].packet = m_packet[num][i - 1].packet + PACKET_SIZE;

  m_SampleRateOutput = channels>2?samplerate:XBMC_SAMPLE_RATE;
  m_BitsPerSampleOutput = 16;

  m_BytesPerSecond = (m_BitsPerSampleOutput / 8)*m_SampleRateOutput*channels;

  /* Open the device */
  int nErr = snd_pcm_open(&m_pStream[num], g_guiSettings.GetString("audiooutput.audiodevice"), SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
    CHECK_ALSA_RETURN(LOGERROR,"pcm_open",nErr);

  /* Allocate Hardware Parameters structures and fills it with config space for PCM */
  snd_pcm_hw_params_alloca(&hw_params);

  nErr = snd_pcm_hw_params_any(m_pStream[num], hw_params);
    CHECK_ALSA_RETURN(LOGERROR,"hw_params_any",nErr);

  nErr = snd_pcm_hw_params_set_access(m_pStream[num], hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);
    CHECK_ALSA_RETURN(LOGERROR,"hw_params_set_access",nErr);

  // always use 16 bit samples
  nErr = snd_pcm_hw_params_set_format(m_pStream[num], hw_params, SND_PCM_FORMAT_S16_LE);
    CHECK_ALSA_RETURN(LOGERROR,"hw_params_set_format",nErr);

  nErr = snd_pcm_hw_params_set_rate_near(m_pStream[num], hw_params, &m_SampleRateOutput, NULL);
    CHECK_ALSA_RETURN(LOGERROR,"hw_params_set_rate",nErr);

  nErr = snd_pcm_hw_params_set_channels(m_pStream[num], hw_params, channels);
    CHECK_ALSA_RETURN(LOGERROR,"hw_params_set_channels",nErr);

    m_periods[num] = PACKET_SIZE / 4;
    nErr = snd_pcm_hw_params_set_period_size_near(m_pStream[num], hw_params, &m_periods[num], 0);
    CHECK_ALSA_RETURN(LOGERROR,"hw_params_set_period_size",nErr);

  snd_pcm_uframes_t buffer_size = PACKET_SIZE*20; // big enough buffer
    nErr = snd_pcm_hw_params_set_buffer_size_near(m_pStream[num], hw_params, &buffer_size);
    CHECK_ALSA_RETURN(LOGERROR,"hw_params_set_buffer_size",nErr);

  unsigned int periodDuration = 0;
  nErr = snd_pcm_hw_params_get_period_time(hw_params,&periodDuration, 0);
    CHECK_ALSA(LOGERROR,"hw_params_get_period_time",nErr);

    CLog::Log(LOGDEBUG,"PAPlayer::CreateStream - initialized. "
         "sample rate: %d, channels: %d, period size: %d, buffer size: %d "
         "period duration: %d",
               m_SampleRateOutput,
         channels,
         (int) m_periods[num],
         (int) buffer_size,
         periodDuration);


    /* Assign them to the playback handle and free the parameters structure */
  nErr = snd_pcm_hw_params(m_pStream[num], hw_params);
    CHECK_ALSA_RETURN(LOGERROR,"snd_pcm_hw_params",nErr);

  /* disable underrun reporting and play silence */
  nErr = snd_pcm_prepare (m_pStream[num]);
    CHECK_ALSA(LOGERROR,"snd_pcm_prepare",nErr);

    // create our resampler  // upsample to XBMC_SAMPLE_RATE, only do this for sources with 1 or 2 channels
    m_resampler[num].InitConverter(samplerate, bitspersample, channels, m_SampleRateOutput, m_BitsPerSampleOutput, PACKET_SIZE);

    // set initial volume
    SetStreamVolume(num, g_stSettings.m_nVolumeLevel);

    // TODO: How do we best handle the callback, given that our samplerate etc. may be
    // changing at this point?

    // fire off our init to our callback
    if (m_pCallback)
      m_pCallback->OnInitialize(channels, m_SampleRateOutput, m_BitsPerSampleOutput);

  return true;
}
开发者ID:Castlecard,项目名称:plex,代码行数:83,代码来源:paplayer_linux.cpp

示例13: sizeof

static void *alsa_thread_init(const char *device,
      unsigned rate, unsigned latency)
{
   alsa_thread_t *alsa = (alsa_thread_t*)calloc(1, sizeof(alsa_thread_t));

   snd_pcm_hw_params_t *params = NULL;
   snd_pcm_sw_params_t *sw_params = NULL;

   const char *alsa_dev = device ? device : "default";

   unsigned latency_usec = latency * 1000 / 2;

   unsigned channels = 2;
   unsigned periods = 4;
   snd_pcm_uframes_t buffer_size;
   snd_pcm_format_t format;

   if (!alsa)
      return NULL;

   TRY_ALSA(snd_pcm_open(&alsa->pcm, alsa_dev, SND_PCM_STREAM_PLAYBACK, 0));

   TRY_ALSA(snd_pcm_hw_params_malloc(&params));
   alsa->has_float = alsathread_find_float_format(alsa->pcm, params);
   format = alsa->has_float ? SND_PCM_FORMAT_FLOAT : SND_PCM_FORMAT_S16;

   TRY_ALSA(snd_pcm_hw_params_any(alsa->pcm, params));
   TRY_ALSA(snd_pcm_hw_params_set_access(
            alsa->pcm, params, SND_PCM_ACCESS_RW_INTERLEAVED));
   TRY_ALSA(snd_pcm_hw_params_set_format(alsa->pcm, params, format));
   TRY_ALSA(snd_pcm_hw_params_set_channels(alsa->pcm, params, channels));
   TRY_ALSA(snd_pcm_hw_params_set_rate(alsa->pcm, params, rate, 0));

   TRY_ALSA(snd_pcm_hw_params_set_buffer_time_near(
            alsa->pcm, params, &latency_usec, NULL));
   TRY_ALSA(snd_pcm_hw_params_set_periods_near(
            alsa->pcm, params, &periods, NULL));

   TRY_ALSA(snd_pcm_hw_params(alsa->pcm, params));

   /* Shouldn't have to bother with this, 
    * but some drivers are apparently broken. */
   if (snd_pcm_hw_params_get_period_size(params, &alsa->period_frames, NULL))
      snd_pcm_hw_params_get_period_size_min(
            params, &alsa->period_frames, NULL);
   RARCH_LOG("ALSA: Period size: %d frames\n", (int)alsa->period_frames);
   if (snd_pcm_hw_params_get_buffer_size(params, &buffer_size))
      snd_pcm_hw_params_get_buffer_size_max(params, &buffer_size);
   RARCH_LOG("ALSA: Buffer size: %d frames\n", (int)buffer_size);

   alsa->buffer_size = snd_pcm_frames_to_bytes(alsa->pcm, buffer_size);
   alsa->period_size = snd_pcm_frames_to_bytes(alsa->pcm, alsa->period_frames);

   TRY_ALSA(snd_pcm_sw_params_malloc(&sw_params));
   TRY_ALSA(snd_pcm_sw_params_current(alsa->pcm, sw_params));
   TRY_ALSA(snd_pcm_sw_params_set_start_threshold(
            alsa->pcm, sw_params, buffer_size / 2));
   TRY_ALSA(snd_pcm_sw_params(alsa->pcm, sw_params));

   snd_pcm_hw_params_free(params);
   snd_pcm_sw_params_free(sw_params);

   alsa->fifo_lock = slock_new();
   alsa->cond_lock = slock_new();
   alsa->cond = scond_new();
   alsa->buffer = fifo_new(alsa->buffer_size);
   if (!alsa->fifo_lock || !alsa->cond_lock || !alsa->cond || !alsa->buffer)
      goto error;

   alsa->worker_thread = sthread_create(alsa_worker_thread, alsa);
   if (!alsa->worker_thread)
   {
      RARCH_ERR("error initializing worker thread");
      goto error;
   }

   return alsa;

error:
   RARCH_ERR("ALSA: Failed to initialize...\n");
   if (params)
      snd_pcm_hw_params_free(params);

   if (sw_params)
      snd_pcm_sw_params_free(sw_params);

   alsa_thread_free(alsa);

   return NULL;
}
开发者ID:AlexFolland,项目名称:RetroArch,代码行数:90,代码来源:alsathread.c

示例14: main

int main()
{
    long loops;
    int rc,i = 0;
    int size;
    FILE *fp ;
    snd_pcm_t *handle;
    snd_pcm_hw_params_t *params;
    unsigned int val,val2;
    int dir;
    snd_pcm_uframes_t frames;
    char *buffer;
    if(  (fp =fopen("sound.wav","w")) < 0)
        printf("open sound.wav fial\n");
    /* Open PCM device for recording (capture). */
    rc = snd_pcm_open(&handle, "default",
                      SND_PCM_STREAM_CAPTURE, 0);
    if (rc < 0)
    {
        fprintf(stderr,  "unable to open pcm device: %s/n",  snd_strerror(rc));
        exit(1);
    }
    /* Allocate a hardware parameters object. */
    snd_pcm_hw_params_alloca(&params);
    /* Fill it in with default values. */
    snd_pcm_hw_params_any(handle, params);
    /* Set the desired hardware parameters. */
    /* Interleaved mode */
    snd_pcm_hw_params_set_access(handle, params,
                                 SND_PCM_ACCESS_RW_INTERLEAVED);
    /* Signed 16-bit little-endian format */
    snd_pcm_hw_params_set_format(handle, params,
                                 SND_PCM_FORMAT_S16_LE);
    /* Two channels (stereo) */
    snd_pcm_hw_params_set_channels(handle, params, 2);
    /* 44100 bits/second sampling rate (CD quality) */
    val = 44100;
    snd_pcm_hw_params_set_rate_near(handle, params,  &val, &dir);
    /* Set period size to 32 frames. */
    frames = 32;
    snd_pcm_hw_params_set_period_size_near(handle,  params, &frames, &dir);
    /* Write the parameters to the driver */
    rc = snd_pcm_hw_params(handle, params);
    if (rc < 0)
    {
        fprintf(stderr,  "unable to set hw parameters: %s/n",
                snd_strerror(rc));
        exit(1);
    }
    /* Use a buffer large enough to hold one period */
    snd_pcm_hw_params_get_period_size(params,  &frames, &dir);
    size = frames * 4; /* 2 bytes/sample, 2 channels */
    printf("size = %d\n",size);
    buffer = (char *) malloc(size);
    /* We want to loop for 5 seconds */
    snd_pcm_hw_params_get_period_time(params,  &val, &dir);
    loops = 10000000 / val;
    while (loops > 0)
    {
        loops--;
        rc = snd_pcm_readi(handle, buffer, frames);
        printf("%d\n",i++);
        if (rc == -EPIPE)
        {
            /* EPIPE means overrun */
            fprintf(stderr, "overrun occurred/n");
            snd_pcm_prepare(handle);
        }
        else if (rc < 0)
        {
            fprintf(stderr,
                    "error from read: %s/n",
                    snd_strerror(rc));
        }
        else if (rc != (int)frames)
        {
            fprintf(stderr, "short read, read %d frames/n", rc);
        }
//rc = fwrite( buffer,1, size,fp);
        rc = write(1,buffer,size);
        if (rc != size)
            fprintf(stderr,  "short write: wrote %d bytes/n", rc);
        else printf("fwrite buffer success\n");
    }
    /******************打印参数*********************/
    snd_pcm_hw_params_get_channels(params, &val);
    printf("channels = %d\n", val);
    snd_pcm_hw_params_get_rate(params, &val, &dir);
    printf("rate = %d bps\n", val);
    snd_pcm_hw_params_get_period_time(params,
                                      &val, &dir);
    printf("period time = %d us\n", val);
    snd_pcm_hw_params_get_period_size(params,
                                      &frames, &dir);
    printf("period size = %d frames\n", (int)frames);
    snd_pcm_hw_params_get_buffer_time(params,
                                      &val, &dir);
    printf("buffer time = %d us\n", val);
    snd_pcm_hw_params_get_buffer_size(params,
                                      (snd_pcm_uframes_t *) &val);
//.........这里部分代码省略.........
开发者ID:renhardly,项目名称:learngit,代码行数:101,代码来源:capture.c

示例15: alsa_stream

static int alsa_stream(const char *pdevice, const char *cdevice, int latency)
{
    snd_pcm_t *phandle, *chandle;
    char *buffer;
    int err;
    ssize_t r;
    struct final_params negotiated;
    snd_pcm_format_t format = SND_PCM_FORMAT_S16_LE;
    char pdevice_new[32];

    err = snd_output_stdio_attach(&output, error_fp, 0);
    if (err < 0) {
        fprintf(error_fp, "alsa: Output failed: %s\n", snd_strerror(err));
        return 0;
    }

    /* Open the devices */
    if ((err = snd_pcm_open(&phandle, pdevice, SND_PCM_STREAM_PLAYBACK,
                            0)) < 0) {
        fprintf(error_fp, "alsa: Cannot open playback device %s: %s\n",
                pdevice, snd_strerror(err));
        return 0;
    }
    if ((err = snd_pcm_open(&chandle, cdevice, SND_PCM_STREAM_CAPTURE,
                            SND_PCM_NONBLOCK)) < 0) {
        fprintf(error_fp, "alsa: Cannot open capture device %s: %s\n",
                cdevice, snd_strerror(err));
        snd_pcm_close(phandle);
        return 0;
    }

    err = setparams(phandle, chandle, format, latency, 0, &negotiated);

    /* Try to use plughw instead, as it allows emulating speed */
    if (err == 2 && strncmp(pdevice, "hw", 2) == 0) {

        snd_pcm_close(phandle);

        sprintf(pdevice_new, "plug%s", pdevice);
        pdevice = pdevice_new;
        if (verbose)
            fprintf(error_fp, "alsa: Trying %s for playback\n", pdevice);
        if ((err = snd_pcm_open(&phandle, pdevice, SND_PCM_STREAM_PLAYBACK,
                                0)) < 0) {
            fprintf(error_fp, "alsa: Cannot open playback device %s: %s\n",
                    pdevice, snd_strerror(err));
            snd_pcm_close(chandle);
            return 0;
        }

        err = setparams(phandle, chandle, format, latency, 1, &negotiated);
    }

    if (err != 0) {
        fprintf(error_fp, "alsa: setparams failed\n");
        snd_pcm_close(phandle);
        snd_pcm_close(chandle);
        return 1;
    }

    buffer = malloc((negotiated.bufsize * snd_pcm_format_width(format) / 8)
                    * negotiated.channels);
    if (buffer == NULL) {
        fprintf(error_fp, "alsa: Failed allocating buffer for audio\n");
        snd_pcm_close(phandle);
        snd_pcm_close(chandle);
        return 0;
    }

    if (verbose)
        fprintf(error_fp,
                "alsa: stream started from %s to %s (%i Hz, buffer delay = %.2f ms)\n",
                cdevice, pdevice, negotiated.rate,
                negotiated.latency * 1000.0 / negotiated.rate);

    while (!stop_alsa) {
        /* We start with a read and not a wait to auto(re)start the capture */
        r = readbuf(chandle, buffer, negotiated.bufsize);
        if (r == 0)   /* Succesfully recovered from an overrun? */
            continue; /* Force restart of capture stream */
        if (r > 0)
            writebuf(phandle, buffer, r);
        /* use poll to wait for next event */
        while (!stop_alsa && !snd_pcm_wait(chandle, 50))
            ;
    }

    snd_pcm_drop(chandle);
    snd_pcm_drop(phandle);

    snd_pcm_unlink(chandle);
    snd_pcm_hw_free(phandle);
    snd_pcm_hw_free(chandle);

    snd_pcm_close(phandle);
    snd_pcm_close(chandle);

    return 0;
}
开发者ID:doriangarcia,项目名称:v4l-utils,代码行数:99,代码来源:alsa_stream.c


注:本文中的snd_pcm_open函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。