Exemplo n.º 1
0
static void open_io(struct holder *holder, const char *filename)
{
	int err;

	if (!strcmp(filename, "-"))
		holder->infile = sf_open_fd(STDIN_FILENO, SFM_READ,
				&holder->ininfo, 1);
	else
		holder->infile = sf_open(filename, SFM_READ, &holder->ininfo);

	if (holder->infile == NULL)
		errx(1, "open in: %s", sf_strerror(NULL));

	err = snd_pcm_open(&holder->alsa_handle, "default",
			SND_PCM_STREAM_PLAYBACK, 0);
	if (err < 0)
		errx(1, "alsa open: %s", snd_strerror(err));

	err = snd_pcm_set_params(holder->alsa_handle, SND_PCM_FORMAT_FLOAT,
			SND_PCM_ACCESS_RW_INTERLEAVED, holder->ininfo.channels,
			holder->ininfo.samplerate, 1, 500000);
	if (err < 0)
		errx(1, "alsa set_params: %s", snd_strerror(err));

	initscr();
	start_color();
	init_pair(1, COLOR_BLUE, COLOR_BLACK);
	init_pair(2, COLOR_WHITE, COLOR_BLACK);
	getmaxyx(stdscr, holder->height, holder->width);
}
Exemplo n.º 2
0
int main(void)
{
	int err;
	unsigned int i;
	snd_pcm_t *handle;
	snd_pcm_sframes_t frames;
	fill_buffer(buffer);
	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,
					11025,
					1,
					500000)) < 0) { /* 0.5sec */
		printf("Playback open error: %s\n", snd_strerror(err));
		exit(EXIT_FAILURE);
	}
	for (i = 0; i < 4; 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(err));
			break;
		}
		if (frames > 0 && frames < (long)sizeof(buffer))
			printf("Short write (expected %li, wrote %li)\n", (long)sizeof(buffer), frames);
	}
	snd_pcm_close(handle);
	return 0;
}
Exemplo n.º 3
0
bool
ManglerAlsa::open(int type, Glib::ustring device, int rate, int channels) {/*{{{*/
    if ((alsa_error = snd_pcm_open(
                          &alsa_stream,
                          (device == "") ? "default" : device.c_str(),
                          (type >= AUDIO_OUTPUT) ? SND_PCM_STREAM_PLAYBACK : SND_PCM_STREAM_CAPTURE,
                          0)) < 0) {
        fprintf(stderr, "alsa: snd_pcm_open() failed: %s\n", snd_strerror(alsa_error));
        alsa_stream = NULL;
        return false;
    }
    if ((alsa_error = snd_pcm_set_params(
                          alsa_stream,                      // pcm handle
                          SND_PCM_FORMAT_S16_LE,            // format
                          SND_PCM_ACCESS_RW_INTERLEAVED,    // access
                          channels,                         // channels
                          rate,                             // rate
                          true,                             // soft_resample
                          150000)) < 0) {                   // latency in usec (0.15 sec)
        fprintf(stderr, "alsa: snd_pcm_set_params() failed: %s\n", snd_strerror(alsa_error));
        close();
        return false;
    }
    if ((alsa_error = snd_pcm_prepare(alsa_stream)) < 0) {
        fprintf(stderr, "alsa: snd_pcm_prepare() failed: %s\n", snd_strerror(alsa_error));
        close();
        return false;
    }
    if (type == AUDIO_INPUT && (alsa_error = snd_pcm_start(alsa_stream)) < 0) {
        fprintf(stderr, "alsa: snd_pcm_start() failed: %s\n", snd_strerror(alsa_error));
        close();
        return false;
    }
    return true;
}/*}}}*/
Exemplo n.º 4
0
/*********************** Main program **********************/
int main(int argc, char **argv)
{
    register int		err;

    // No wave data loaded yet
    WavePtr = 0;

    if (argc < 2)
    {
        printf("You must supply the name of a 16-bit mono WAVE file to play\n");
        return 0;
    }

    // Load the wave file
    if (waveLoad(argv[1]))
    {
        printf("Could not load wave file\n");
        return 0;
    }

    if(WaveBits != 16)
    {
        printf("16 bit PCM audio only!!!\n");
        return 0;
    }

    printf("Sample total %d\n", WaveSize);
    printf("Sample rate  %d\n", WaveRate);
    printf("Sample bits  %d\n", WaveBits);
    add_effect(fuzz_init, fuzz_run, fuzz_end, "Fuzz");
    printf("Finished effect line\n");

    // Open audio card we wish to use for playback
    if ((err = snd_pcm_open(&PlaybackHandle, &SoundCardPortName[0], SND_PCM_STREAM_PLAYBACK, 0)) < 0)
    {
        printf("Can't open audio %s: %s\n", &SoundCardPortName[0], snd_strerror(err));
        return 0;
    }

    // Set the audio card's hardware parameters (sample rate, bit resolution, etc)
    if ((err = snd_pcm_set_params(PlaybackHandle, SND_PCM_FORMAT_S16, SND_PCM_ACCESS_RW_INTERLEAVED, WaveChannels, WaveRate, 1, 10000)) < 0)
    {
        printf("Can't set sound parameters: %s\n", snd_strerror(err));
        return 0;
    }

    // Play the waveform
    play_audio();

    // Close sound card
    snd_pcm_close(PlaybackHandle);

    // Free the WAVE data
    free_wave_data();

    return 0;
}
int nv_alsa_init(unsigned int channelCount, unsigned int sampleRate, unsigned char* device) {
	int rc;
	
	/* Open PCM device for playback. */
	if ((rc = snd_pcm_open(&handle, device, SND_PCM_STREAM_PLAYBACK, 0)) != 0)
		return rc;
	
	if ((rc = snd_pcm_set_params(handle, SND_PCM_FORMAT_S16_LE, SND_PCM_ACCESS_RW_INTERLEAVED, channelCount, sampleRate, 1, 50000)) != 0) //50ms latency
		return rc;
}
Exemplo n.º 6
0
void initialize(snd_pcm_t *capture_handle) {

	  int err;
	    if ((err = snd_pcm_set_params(capture_handle,
	                                  format,
	                                  SND_PCM_ACCESS_RW_INTERLEAVED,
	                                  2,
									  44100,
	                                  0,
	                                  50000)) < 0) {   /* 0.5sec */
	            printf("Playback open error: %s\n", snd_strerror(err));
	            exit(EXIT_FAILURE);
	    }
}
Exemplo n.º 7
0
/*Function Name: setParams
Parameters: sampling rate
Description: Set the sampling rate*/
void setParams(int samp)
{
	err = snd_pcm_set_params(handle,
		SND_PCM_FORMAT_S16_LE,
		SND_PCM_ACCESS_RW_INTERLEAVED,
		2,
		samp,
		1,
		500000);
	if ((err) < 0) { /* 0.5sec */
			printf("Playback open error: %s\n", snd_strerror(err));
			exit(EXIT_FAILURE);
	}
}
Exemplo n.º 8
0
static int pcm_open (void)
{
    if (snd_pcm_open(&handle, "default", SND_PCM_STREAM_PLAYBACK, 0) < 0) {
        perror("snd_pcm_open");
        return -1;
    }

    if (snd_pcm_set_params(
            handle, SND_PCM_FORMAT_U8, SND_PCM_ACCESS_RW_INTERLEAVED, 1, 8000, 1, 200000) < 0) {
        perror("snd_pcm_set_params");
        return -1;
    }

    return 0;
}
Exemplo n.º 9
0
int main(int argc, char *argv[]) {
	const static char *device = "default";
	snd_output_t *output = NULL;
	float buffer[BUFFER_LEN];
	int err;
	int k;

	snd_pcm_t *handle;
	snd_pcm_sframes_t frames;

	if ((err = snd_pcm_open(&handle, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
		fprintf(stderr, "AlsaTone: Playback open error: %s\n", snd_strerror(err));
		return EXIT_FAILURE;
	}

	if ((err = snd_pcm_set_params(handle,
			SND_PCM_FORMAT_FLOAT,
			SND_PCM_ACCESS_RW_INTERLEAVED,
			1,
			BUFFER_LEN,
			1,
			500000)) < 0) {	 
		fprintf(stderr, "AlsaTone: Playback open error: %s\n", snd_strerror(err));
		return EXIT_FAILURE;
	}

	// SINE WAVE
	int freq = (argc > 1) ? strtol(argv[1], NULL, 10) : DEFAULT_FREQ;
	if (freq == 0) {
		fprintf(stderr, "AlsaTone: Invalid frequency.\n");
		return EXIT_FAILURE;
	}
	int duration = (argc > 2) ? strtol(argv[2], NULL, 10) : DEFAULT_DURATION;
	if (duration == 0) {
		fprintf(stderr, "AlsaTone: Invalid duration.\n");
		return EXIT_FAILURE;
	}
	printf("Sine tone at %dHz during %d seconds.\n", freq, duration);
	
	for (k=0 ; k<BUFFER_LEN ; k++)
		buffer[k] = sin(2*M_PI * freq / BUFFER_LEN * k); // Creating the sinusoid
	
	for (k=0 ; k < duration ; k++)
		frames = snd_pcm_writei(handle, buffer, BUFFER_LEN); // Sending the sound

	snd_pcm_close(handle);
	return EXIT_SUCCESS;
}
Exemplo n.º 10
0
// midi init
MIDI_RESULT MIDI_Init()
{
    EAS_RESULT result;

    // get the library configuration
    pLibConfig = EAS_Config();
    if ((pLibConfig == NULL) || (pLibConfig->libVersion != LIB_VERSION))
	return MIDI_FAILURE;

    // init library
    if ((result = EAS_Init(&pEASData)) != EAS_SUCCESS)
        return result;

    // select reverb preset and enable
    EAS_SetParameter(pEASData, EAS_MODULE_REVERB, EAS_PARAM_REVERB_PRESET,
		     EAS_PARAM_REVERB_CHAMBER);
    EAS_SetParameter(pEASData, EAS_MODULE_REVERB, EAS_PARAM_REVERB_BYPASS,
		     EAS_FALSE);

    // open pcm stream
    if ((result = snd_pcm_open(&handle, device,
			       SND_PCM_STREAM_PLAYBACK, 0)) < 0)
	return result;

    // set stream parameters: 16bit, interleaved, channels and sample
    // rate from the EAS config and 50ms latency
    if ((result = snd_pcm_set_params(handle, SND_PCM_FORMAT_S16,
				     SND_PCM_ACCESS_RW_INTERLEAVED,
				     pLibConfig->numChannels,
				     pLibConfig->sampleRate,
				     1, 50000)) < 0)
	return result;

    // calculate buffer size in samples
    bufferSize = pLibConfig->mixBufferSize * pLibConfig->numChannels *
	NUM_BUFFERS;

    // allocate buffer in bytes
    buffer = malloc(bufferSize * sizeof(EAS_PCM));

    // clear flag
    flag = FALSE;

    // start rendering thread
    pthread_create(&thread, NULL, render, NULL);

    return MIDI_SUCCESS;
}
Exemplo n.º 11
0
void set_up_sound(snd_pcm_t **playback_handle, int encoding_type, 
    uint32_t channels, uint32_t sample_rate) {
  
  int err;
  if ((err = snd_pcm_open (playback_handle, "default", SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
    fprintf (stderr, "cannot open audio device (%s)\n", snd_strerror (err));
    exit (1);
  }

  err = snd_pcm_set_params(*playback_handle, encoding_type, SND_PCM_ACCESS_RW_INTERLEAVED, channels, sample_rate, 1, 500000); 

  if ((err = snd_pcm_prepare (*playback_handle)) < 0) {
    fprintf (stderr, "cannot prepare audio interface for use (%s)\n",
        snd_strerror (err));
    exit (1);
  }
}
int CMAlsaAudioSink::init()
{
    int err;

    if ((err = snd_pcm_set_params(handle, SND_PCM_FORMAT_S16_LE, SND_PCM_ACCESS_RW_INTERLEAVED, m_channels, m_rate, 1, 100000)) < 0) {
        qDebug() << "Set params error: " << snd_strerror(err);
        return false;
    }
#if 0
    if (m_resampler)
        speex_resampler_destroy(m_resampler);

    m_resampler=speex_resampler_init(m_channels, m_rate, m_srate, 10, &err);
#endif

    return true;
}
Exemplo n.º 13
0
int output_alsa_open(struct output **handle, unsigned long samplerate,
		     unsigned char channels, unsigned int latency)
{
	struct output *h;
	int ret;

	/* Allocate handle */
	*handle = malloc(sizeof(struct output));
	if(*handle == NULL)
		return -1;
	h = *handle;

	/* Init structure */
	h->streams = NULL;
	h->stop = 0;

	/* Copy input and output format */
	h->samplerate = samplerate;
	h->channels = channels;
	h->volume = OUTPUT_VOLUME_MAX;

	/* Open alsa device */
	if(snd_pcm_open(&h->alsa, "default", SND_PCM_STREAM_PLAYBACK, 0) < 0)
		return -1;

	/* Set latency to default */
	if(latency < MIN_LATENCY)
		latency = MIN_LATENCY;

	/* Set parameters for output */
	ret = snd_pcm_set_params(h->alsa, ALSA_FORMAT,
				 SND_PCM_ACCESS_RW_INTERLEAVED, h->channels,
				 h->samplerate, 1, latency*1000);
	if(ret < 0)
		return -1;

	/* Initialize mutex */
	pthread_mutex_init(&h->mutex, NULL);

	/* Create thread */
	if(pthread_create(&h->thread, NULL, output_alsa_thread, h) != 0)
		return -1;

	return 0;
}
Exemplo n.º 14
0
int audio_init(struct audio **audiop)
{
	struct audio *audio;
	int err;

	audio = malloc(sizeof(*audio));
	if (audio == NULL) {
		return errno;
	}
	memset(audio, 0, sizeof(*audio));

	err = snd_pcm_open(&audio->pcm, "default",
			   SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
	if (err < 0) {
		fprintf(stderr, "%s(): %d: %s\n", __func__, err, snd_strerror(err));
		audio_free(audio);
		return -err;
	}

	err = snd_pcm_set_params(audio->pcm, SND_PCM_FORMAT_S16_LE,
				 SND_PCM_ACCESS_RW_INTERLEAVED,
				 2, 44100,
				 1, /* allow resampling */
				 1 * 1000000); /* latency (1s) */

	if (err < 0) {
		fprintf(stderr, "%s(): snd_pcm_set_params(): %d (%s)\n",
			__func__, err, snd_strerror(err));
		audio_free(audio);
		return -err;
	}

	err = snd_pcm_prepare(audio->pcm);
	if (err < 0) {
		fprintf(stderr, "%s(): snd_pcm_prepare(): %d (%s)\n",
			__func__, err, snd_strerror(err));
		audio_free(audio);
		return -err;
	}


	*audiop = audio;
	return -err;
}
Exemplo n.º 15
0
// On error return a negative value
// If the requested buffer size can be served return 0,
// otherwise return the number of 16 bit words contained in the obtained buffer
mp_sint32 AudioDriver_ALSA::initDevice(mp_sint32 periodSizeAsSamples, const mp_uint32 mixFrequency, MasterMixer* mixer)
{
	snd_pcm_sw_params_t *swparams;
	snd_pcm_uframes_t buffer_size;
	int err;

	snd_pcm_sw_params_alloca(&swparams);

	if ((err = snd_pcm_open(&pcm, "default", SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
		fprintf(stderr, "ALSA: Failed to open device 'default' (%s)\n", snd_strerror(err));
		return -1;
	}

	if ((err = snd_pcm_set_params(pcm,
		SND_PCM_FORMAT_S16,
		SND_PCM_ACCESS_MMAP_INTERLEAVED,
		2, // channels
		mixFrequency,
		0, // disallow soft resampling
		(2000000 * static_cast<unsigned long long> (periodSizeAsSamples)) / mixFrequency)) < 0)
			// period size in uS
	{
		fprintf(stderr, "ALSA: Playback open error (%s)\nALSA: Is your mixer frequency correct? Try 48000Hz\nALSA: If you are seeing \"Access type not available for PLAYBACK\" then your audio driver does not support MMAP access, and will not work with this version of MilkyTracker using the ALSA driver (try SDL instead).\n", snd_strerror(err));
		return -1;
	}

	snd_pcm_prepare(pcm);
	period_size = periodSizeAsSamples * 2;
	snd_pcm_get_params(pcm, &buffer_size, &period_size);
	stream = new char[period_size * 2];
	printf("ALSA: Period size = %lu frames (requested %i), buffer size = %lu frames\n", period_size, periodSizeAsSamples / 2, buffer_size);

	/* get the current swparams */
	err = snd_pcm_sw_params_current(pcm, swparams);
	if (err < 0) {
		fprintf(stderr, "ALSA: Unable to determine current swparams for playback: %s\n", snd_strerror(err));
		return -1;
	}

	AudioDriverBase::initDevice(period_size * 2, mixFrequency, mixer);
	return period_size * 2;		// 2 = number of channels
}
Exemplo n.º 16
0
/**
   初始化 pcm 
*/
void init_playback_p(){
    printf("init_playback\n");
    int err;

    if ((err = snd_pcm_open(&PCM_HANDLE, PCM_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(PCM_HANDLE,
                                  SND_PCM_FORMAT_S16_LE,
                                  SND_PCM_ACCESS_RW_INTERLEAVED,
                                  CHANNELS,
                                  RATE,
                                  1,
                                  LATENCY)) < 0) {   /* 0.5sec */
            printf("Playback open error: %s\n", snd_strerror(err));
            // exit(EXIT_FAILURE);
    }
    //open audio file
    int ret;
}
Exemplo n.º 17
0
/* initialize ALSA */
static void alsa_init(audio_dev_handle* handle)
{
    int err;

    /* Set up the sound card */
    if ( (err = snd_pcm_open(&handle->alsa_handle, "default", SND_PCM_STREAM_PLAYBACK, 0)) < 0 )
    {
        printf("snd_pcm_open failed: %s\n", snd_strerror(err));
        exit(EXIT_FAILURE);
    }

    if ( (err = snd_pcm_set_params(handle->alsa_handle,
                                   handle->format,
                                   SND_PCM_ACCESS_RW_INTERLEAVED,
                                   handle->channels,
                                   handle->rate,
                                   1, /* allow resampling */
                                   handle->latency * 1000)) < 0) {
        printf("snd_pcm_set_params failed: %s\n", snd_strerror(err));
	exit(EXIT_FAILURE);
    }
}
Exemplo n.º 18
0
void beepStartSpeech(void)
{
    int err;
    int j,k;

    int f = 2000;                //frequency 1
    int fs = 48000;             //sampling frequency

    snd_pcm_t *handle;
    snd_pcm_sframes_t frames;


    // ERROR HANDLINGii

    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_FLOAT, SND_PCM_ACCESS_RW_INTERLEAVED, 1, 48000, 1, 500000)) < 0) {   
            printf("Playback open error: %s\n", snd_strerror(err));
            exit(EXIT_FAILURE);
    }

    // SINE WAVE
    printf("Sine tone at %dHz", f);

        for (k = 0; k < BUFFER_LEN; k++)
            buffer[k] = (1 / ((float) exp(2*k / 880.0))) * sin(2 * M_PI * f / fs * k);                 //sine wave value generation                        

        for (j = 0; j < 1; j++)
            frames = snd_pcm_writei(handle, buffer, BUFFER_LEN);    //sending values to sound driver
            

    snd_pcm_close(handle);

}
Exemplo n.º 19
0
static int
alsa_stream_init(cubeb * ctx, cubeb_stream ** stream, char const * stream_name,
                 cubeb_stream_params stream_params, unsigned int latency,
                 cubeb_data_callback data_callback, cubeb_state_callback state_callback,
                 void * user_ptr)
{
  cubeb_stream * stm;
  int r;
  snd_pcm_format_t format;

  assert(ctx && stream);

  *stream = NULL;

  switch (stream_params.format) {
  case CUBEB_SAMPLE_S16LE:
    format = SND_PCM_FORMAT_S16_LE;
    break;
  case CUBEB_SAMPLE_S16BE:
    format = SND_PCM_FORMAT_S16_BE;
    break;
  case CUBEB_SAMPLE_FLOAT32LE:
    format = SND_PCM_FORMAT_FLOAT_LE;
    break;
  case CUBEB_SAMPLE_FLOAT32BE:
    format = SND_PCM_FORMAT_FLOAT_BE;
    break;
  default:
    return CUBEB_ERROR_INVALID_FORMAT;
  }

  pthread_mutex_lock(&ctx->mutex);
  if (ctx->active_streams >= CUBEB_STREAM_MAX) {
    pthread_mutex_unlock(&ctx->mutex);
    return CUBEB_ERROR;
  }
  ctx->active_streams += 1;
  pthread_mutex_unlock(&ctx->mutex);

  stm = calloc(1, sizeof(*stm));
  assert(stm);

  stm->context = ctx;
  stm->data_callback = data_callback;
  stm->state_callback = state_callback;
  stm->user_ptr = user_ptr;
  stm->params = stream_params;
  stm->state = INACTIVE;

  r = pthread_mutex_init(&stm->mutex, NULL);
  assert(r == 0);

  r = alsa_locked_pcm_open(&stm->pcm, SND_PCM_STREAM_PLAYBACK, ctx->local_config);
  if (r < 0) {
    alsa_stream_destroy(stm);
    return CUBEB_ERROR;
  }

  r = snd_pcm_nonblock(stm->pcm, 1);
  assert(r == 0);

  /* Ugly hack: the PA ALSA plugin allows buffer configurations that can't
     possibly work.  See https://bugzilla.mozilla.org/show_bug.cgi?id=761274.
     Only resort to this hack if the handle_underrun workaround failed. */
  if (!ctx->local_config && ctx->is_pa) {
    latency = latency < 500 ? 500 : latency;
  }

  r = snd_pcm_set_params(stm->pcm, format, SND_PCM_ACCESS_RW_INTERLEAVED,
                         stm->params.channels, stm->params.rate, 1,
                         latency * 1000);
  if (r < 0) {
    alsa_stream_destroy(stm);
    return CUBEB_ERROR_INVALID_FORMAT;
  }

  r = snd_pcm_get_params(stm->pcm, &stm->buffer_size, &stm->period_size);
  assert(r == 0);

  stm->nfds = snd_pcm_poll_descriptors_count(stm->pcm);
  assert(stm->nfds > 0);

  stm->saved_fds = calloc(stm->nfds, sizeof(struct pollfd));
  assert(stm->saved_fds);
  r = snd_pcm_poll_descriptors(stm->pcm, stm->saved_fds, stm->nfds);
  assert((nfds_t) r == stm->nfds);

  r = pthread_cond_init(&stm->cond, NULL);
  assert(r == 0);

  if (alsa_register_stream(ctx, stm) != 0) {
    alsa_stream_destroy(stm);
    return CUBEB_ERROR;
  }

  *stream = stm;

  return CUBEB_OK;
}
Exemplo n.º 20
0
int
ALSAAudio_init(output_ALSAAudio *self, PyObject *args, PyObject *kwds)
{
    PyObject *audiotools_pcm = NULL;
    char *device;
    int sample_rate = 44100;
    int channels = 2;
    int bits_per_sample = 16;
    int error;
    snd_pcm_format_t output_format = SND_PCM_FORMAT_S16_LE;

    self->framelist_type = NULL;
    self->output = NULL;
    self->mixer = NULL;
    self->mixer_elem = NULL;
    self->buffer_size = 0;

    /*get FrameList type for comparison during .play() operation*/
    if ((audiotools_pcm = open_audiotools_pcm()) != NULL) {
        self->framelist_type = PyObject_GetAttrString(audiotools_pcm,
                                                      "FrameList");
        Py_DECREF(audiotools_pcm);
        if (self->framelist_type == NULL) {
            /*unable to get audiotools.pcm.FrameList type*/
            return -1;
        }
    } else {
        /*unable to open audiotools.pcm module*/
        return -1;
    }

    if (!PyArg_ParseTuple(args, "siii",
                          &device,
                          &sample_rate,
                          &channels,
                          &bits_per_sample))
        return -1;

    /*sanity check output parameters*/
    if (sample_rate > 0) {
        self->sample_rate = sample_rate;
    } else {
        PyErr_SetString(
            PyExc_ValueError, "sample rate must be a postive value");
        return -1;
    }

    if (channels > 0) {
        self->channels = channels;
    } else {
        PyErr_SetString(
            PyExc_ValueError, "channels must be a positive value");
        return -1;
    }

    switch (bits_per_sample) {
    case 8:
        self->bits_per_sample = bits_per_sample;
        self->buffer.int8 = NULL;
        self->play = play_8_bps;
        output_format = SND_PCM_FORMAT_S8;
        break;
    case 16:
        self->bits_per_sample = bits_per_sample;
        self->buffer.int16 = NULL;
        self->play = play_16_bps;
        output_format = SND_PCM_FORMAT_S16;
        break;
    case 24:
        self->bits_per_sample = bits_per_sample;
        self->buffer.int32 = NULL;
        self->play = play_24_bps;
        output_format = SND_PCM_FORMAT_S32;
        //output_format = SND_PCM_FORMAT_FLOAT;
        break;
    default:
        PyErr_SetString(
            PyExc_ValueError, "bits-per-sample must be 8, 16 or 24");
        return -1;
    }

    if ((error = snd_pcm_open(&self->output,
                              device,
                              SND_PCM_STREAM_PLAYBACK,
                              0)) < 0) {
        PyErr_SetString(PyExc_IOError, "unable to open ALSA output handle");
        return -1;
    }

    if ((error = snd_pcm_set_params(self->output,
                                    output_format,
                                    SND_PCM_ACCESS_RW_INTERLEAVED,
                                    channels,
                                    sample_rate,
                                    1,
                                    500000)) < 0) {
        PyErr_SetString(PyExc_IOError, "unable to set ALSA stream parameters");
        return -1;
    }

    if ((error = snd_mixer_open(&self->mixer, 0)) < 0) {
        /*unable to open ALSA mixer*/
        self->mixer = NULL;
        return 0;
    } else if ((error = snd_mixer_attach(self->mixer, device)) < 0) {
        /*unable to attach mixer to card*/
        snd_mixer_close(self->mixer);
        self->mixer = NULL;
        return 0;
    } else if ((error = snd_mixer_selem_register(self->mixer,
                                                 NULL,
                                                 NULL)) < 0) {
        /*unable to register mixer*/
        snd_mixer_close(self->mixer);
        self->mixer = NULL;
        return 0;
    } else if ((error = snd_mixer_load(self->mixer)) < 0) {
        /*unable to load mixer*/
        snd_mixer_close(self->mixer);
        self->mixer = NULL;
        return 0;
    }

    /*walk through mixer elements to find Master or PCM*/
    self->mixer_elem = find_playback_mixer_element(self->mixer, "Master");
    if (self->mixer_elem == NULL) {
        /*this may be NULL if no Master or PCM found*/
        self->mixer_elem = find_playback_mixer_element(self->mixer, "PCM");
    }
    if (self->mixer_elem != NULL) {
        snd_mixer_selem_get_playback_volume_range(self->mixer_elem,
                                                  &self->volume_min,
                                                  &self->volume_max);
    }

    return 0;
}
Exemplo n.º 21
0
int main( int argc, char* argv[] ) {

  printf("Sizeof buffer[16*1024] = %d \n", sizeof(buffer) );
  
  int err;
  unsigned int i;
  snd_pcm_t *handle;
  snd_pcm_sframes_t frames;
  
  int vol = 64;
  double sample_rate = 44100; // Hz
  double frequency = 261.625565;
  int channels = 1;
  int allow_resampling = 1;

  for (i = 0; i < sizeof(buffer); i++) {
    //  buffer[i] = random() & 0xff;
    buffer[i] = vol*(1 + sin(i*2*3.1416/sample_rate*frequency) );
  }


  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,
				channels,
				sample_rate,
				allow_resampling,
				500000)) < 0) {   /* 0.5sec */
    printf("Playback open error: %s\n", snd_strerror(err));
    exit(EXIT_FAILURE);
  }
   
  time_t ts, tf;
  double dt;
  for (i = 0; i < 20; i++) {
    ts = time(NULL);
    printf("Try 16 time? i=%d \n", 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);
    } else if( frames == sizeof(buffer) ) {
      printf("The same size! \n");
    }
    
    tf = time(NULL);
    dt = (double)(tf-ts);
    printf("Dt in for [%d] : %f \n", i, dt);
  }

  printf("Closing \n");
  snd_pcm_close(handle);
  return 0;
}
Exemplo n.º 22
0
static int aplaypop_open(void)
{
    int err;
    snd_pcm_t *handle;

    if (pcm_handle)
        return 0;

    snd_pcm_info_t *info;
    snd_pcm_info_alloca(&info);

    snd_output_t *log;
    err = snd_output_stdio_attach(&log, stderr, 0);
    assert(err == 0);

    err = snd_pcm_open(&handle, device, SND_PCM_STREAM_PLAYBACK, 0);
    if (err != 0) {
        fprintf(stderr, "snd_pcm_open(): %s\n", snd_strerror(err));
        exit(EXIT_FAILURE);
    }
    err = snd_pcm_nonblock(handle, 0);
    if (err != 0) {
        fprintf(stderr, "snd_pcm_nonblock(): %s\n", snd_strerror(err));
        exit(EXIT_FAILURE);
    }
    err = snd_pcm_info(handle, info);
    if (err != 0) {
        fprintf(stderr, "snd_pcm_info(): %s\n", snd_strerror(err));
        exit(EXIT_FAILURE);
    }

    // DOESN'T WORK!
    err = snd_pcm_set_params(handle, SND_PCM_FORMAT_S16_LE,
        SND_PCM_ACCESS_RW_INTERLEAVED, CHANNELS, RATE, 1, 50000);
    if (err != 0) {
        fprintf(stderr, "snd_pcm_set_params(): %s\n", snd_strerror(err));
        exit(EXIT_FAILURE);
    }

    // RIGHT WAY:
    snd_pcm_hw_params_t *hwparams;
    snd_pcm_sw_params_t *swparams;

    snd_pcm_format_t format = SND_PCM_FORMAT_S16_LE;
    unsigned int channels = CHANNELS;
    unsigned int rate = RATE;

    snd_pcm_hw_params_alloca(&hwparams);
    snd_pcm_sw_params_alloca(&swparams);

    err = snd_pcm_hw_params_any(handle, hwparams);
    if (err != 0) {
        fprintf(stderr, "Broken configuration for this PCM: %s\n", snd_strerror(err));
        exit(EXIT_FAILURE);
    }
    err = snd_pcm_hw_params_set_access(handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED);
    if (err != 0) {
        fprintf(stderr, "snd_pcm_hw_params_set_access(): %s\n", snd_strerror(err));
        exit(EXIT_FAILURE);
    }
    err = snd_pcm_hw_params_set_format(handle, hwparams, format);
    if (err != 0) {
        fprintf(stderr, "snd_pcm_hw_params_set_format(): %s\n", snd_strerror(err));
        exit(EXIT_FAILURE);
    }
    err = snd_pcm_hw_params_set_channels(handle, hwparams, channels);
    if (err != 0) {
        fprintf(stderr, "snd_pcm_hw_params_set_channels(): %s\n", snd_strerror(err));
        exit(EXIT_FAILURE);
    }
    err = snd_pcm_hw_params_set_rate_near(handle, hwparams, &rate, 0);
    if (err != 0) {
        fprintf(stderr, "snd_pcm_hw_params_set_rate_near(): %s\n", snd_strerror(err));
        exit(EXIT_FAILURE);
    }
/*
    unsigned buffer_time = 0;
    snd_pcm_uframes_t buffer_frames = 0;

    if (buffer_time == 0 && buffer_frames == 0) {
        err = snd_pcm_hw_params_get_buffer_time_max(hwparams, &buffer_time, 0);
        assert(err == 0);
        if (buffer_time > 500000)
            buffer_time = 500000;
    }

    unsigned period_time = 0;
    snd_pcm_uframes_t period_frames = 0;

    if (period_time == 0 && period_frames == 0) {
        if (buffer_time > 0)
            period_time = buffer_time / 4;
        else
            period_frames = buffer_frames / 4;
    }

    if (period_time > 0)
        err = snd_pcm_hw_params_set_period_time_near(handle, hwparams, &period_time, 0);
    else
        err = snd_pcm_hw_params_set_period_size_near(handle, hwparams, &period_frames, 0);
    assert(err == 0);

    if (buffer_time > 0)
        err = snd_pcm_hw_params_set_buffer_time_near(handle, hwparams, &buffer_time, 0);
    else
        err = snd_pcm_hw_params_set_buffer_size_near(handle, hwparams, &buffer_frames);
    assert(err == 0);

    int monotonic = snd_pcm_hw_params_is_monotonic(hwparams);
    int can_pause = snd_pcm_hw_params_can_pause(hwparams);
*/
    err = snd_pcm_hw_params(handle, hwparams);
    if (err != 0) {
        fprintf(stderr, "snd_pcm_hw_params(): %s\n", snd_strerror(err));
        snd_pcm_hw_params_dump(hwparams, log);
        exit(EXIT_FAILURE);
    }
    snd_pcm_uframes_t chunk_size = 0;
    snd_pcm_hw_params_get_period_size(hwparams, &chunk_size, 0);
    snd_pcm_uframes_t buffer_size;
    snd_pcm_hw_params_get_buffer_size(hwparams, &buffer_size);
    if (chunk_size == buffer_size) {
        fprintf(stderr, "Can't use period equal to buffer size (%lu == %lu)",
              chunk_size, buffer_size);
        exit(EXIT_FAILURE);
    }
    snd_pcm_sw_params_current(handle, swparams);

    err = snd_pcm_sw_params_set_avail_min(handle, swparams, chunk_size);
    assert(err == 0);

    /* round up to closest transfer boundary */
    int start_delay = 0;
    snd_pcm_uframes_t start_threshold;
    if (start_delay <= 0)
        start_threshold = buffer_size + (double) rate * start_delay / 1000000;
    else
        start_threshold = (double) rate * start_delay / 1000000;
    start_threshold = start_threshold < 1 ? 1 : start_threshold > buffer_size ? buffer_size : start_threshold;
    err = snd_pcm_sw_params_set_start_threshold(handle, swparams, start_threshold);
    assert(err == 0);

    int stop_delay = 0;
    snd_pcm_uframes_t stop_threshold;
    if (stop_delay <= 0)
        stop_threshold = buffer_size + (double) rate * stop_delay / 1000000;
    else
        stop_threshold = (double) rate * stop_delay / 1000000;
    err = snd_pcm_sw_params_set_stop_threshold(handle, swparams, stop_threshold);
    assert(err == 0);

    err = snd_pcm_sw_params(handle, swparams);
    if (err != 0) {
        fprintf(stderr, "snd_pcm_sw_params(): %s\n", snd_strerror(err));
        snd_pcm_sw_params_dump(swparams, log);
        exit(EXIT_FAILURE);
    }
    // END OF THE RIGHT WAY

//  snd_pcm_dump(handle, log);

    size_t bits_per_sample = snd_pcm_format_physical_width(format);
    size_t bits_per_frame = bits_per_sample * channels;
    size_t chunk_bytes = chunk_size * bits_per_frame / 8;
    //audiobuf = realloc(audiobuf, chunk_bytes);

    fprintf(stderr, "%s: %s, Rate %d Hz, Channels=%u\n",
        snd_pcm_format_name(format), snd_pcm_format_description(format),
        rate, channels);
    fprintf(stderr, "  bits_per_sample=%u, bits_per_frame=%u, chunk_bytes=%u\n",
        bits_per_sample, bits_per_frame, chunk_bytes);

    frame_bytes = bits_per_frame / 8;
    pcm_handle = handle;
    return 0;
}
Exemplo n.º 23
0
void audio_dma_start()
{
    int err;
    unsigned int i, j;

    for (i = 0; i < NUM_BUFFERS; i++) {
        for (j = 0; j < NUM_SAMPLES; j++) {
            g_rec_buffers[i][j] = 0;
            g_play_buffers[i][j] = 0;
        }
    }

    if ((err = snd_pcm_open(
                   &g_handle_rec, device, SND_PCM_STREAM_CAPTURE, 0
               )) < 0)
    {
        printf("Capture open error: %s\n", snd_strerror(err));
        exit(EXIT_FAILURE);
    }
    if ((err = snd_pcm_open(
                   &g_handle_play, 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(g_handle_rec,
                                  SND_PCM_FORMAT_S32_LE,
                                  SND_PCM_ACCESS_RW_INTERLEAVED,
                                  NUM_CHANNELS,
                                  48000,
                                  0, /* disallow resampling */
                                  1000)) < 0) {   /* 1 msec */
        printf("Capture open error: %s\n", snd_strerror(err));
        exit(EXIT_FAILURE);
    }
    if ((err = snd_pcm_set_params(g_handle_play,
                                  SND_PCM_FORMAT_S32_LE,
                                  SND_PCM_ACCESS_RW_INTERLEAVED,
                                  NUM_CHANNELS,
                                  48000,
                                  0, /* disallow resampling */
                                  1000)) < 0) {   /* 1 msec */
        printf("Playback open error: %s\n", snd_strerror(err));
        exit(EXIT_FAILURE);
    }

    err = sem_init(&g_empty_cnt_sem, 0, NUM_BUFFERS);
    if (err < 0) {
        printf("sem_init error: %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }
    err = sem_init(&g_full_cnt_sem, 0, 0);
    if (err < 0) {
        printf("sem_init error: %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }

    err = pthread_create(
              &g_h_reader_thread, NULL, reader_thread, NULL
          );
    if (err < 0) {
        printf("pthread_create error: %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }

    err = pthread_create(
              &g_h_writer_thread, NULL, writer_thread, NULL
          );
    if (err < 0) {
        printf("pthread_create error: %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }
}
Exemplo n.º 24
0
static int
sa_alsa_open_stream(
		simpleaudio *sa,
		const char *backend_device,
		sa_direction_t sa_stream_direction,
		sa_format_t sa_format,
		unsigned int rate, unsigned int channels,
		char *app_name, char *stream_name )
{
    snd_pcm_t *pcm;
    int error;

    char *be_device;
    if ( ! backend_device ) {
	be_device = "default";
    } else {
	be_device = alloca(32);
	if ( strchr(backend_device, ':') )
	    snprintf(be_device, 32, "%s", backend_device);
	else if ( strchr(backend_device, ',') )
	    snprintf(be_device, 32, "plughw:%s", backend_device);
	else
	    snprintf(be_device, 32, "plughw:%s,0", backend_device);
    }

    error = snd_pcm_open(&pcm,
		be_device,
		sa_stream_direction == SA_STREAM_RECORD ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
		0 /*mode*/);
    if (error) {
	fprintf(stderr, "E: Cannot create ALSA stream: %s\n", snd_strerror(error));
	return 0;
    }

    snd_pcm_format_t pcm_format;

    switch ( sa->format ) {
	case SA_SAMPLE_FORMAT_FLOAT:
		pcm_format = SND_PCM_FORMAT_FLOAT;
		break;
	case SA_SAMPLE_FORMAT_S16:
		pcm_format = SND_PCM_FORMAT_S16;
		break;
	default:
		assert(0);
    }

    /* set up ALSA hardware params */
    error = snd_pcm_set_params(pcm,
		pcm_format,
		SND_PCM_ACCESS_RW_INTERLEAVED,
		channels,
		rate,
		1 /* soft_resample (allow) */,
		(unsigned int)-1 /* latency (allow max to avoid underruns) */);
    if (error) {
	fprintf(stderr, "E: %s\n", snd_strerror(error));
	snd_pcm_close(pcm);
	return 0;
    }

#if 0
    snd_pcm_sw_params_t  *swparams;
    snd_pcm_sw_params_alloca(&swparams);
    error = snd_pcm_sw_params_current(pcm, swparams);
    if (error) {
	fprintf(stderr, "E: %s\n", snd_strerror(error));
	snd_pcm_close(pcm);
	return NULL;
    }
    snd_pcm_sw_params_set_start_threshold(pcm, swparams, NFRAMES_VAL);
    snd_pcm_sw_params_set_stop_threshold(pcm, swparams, NFRAMES_VAL);
    snd_pcm_sw_params_set_silence_threshold(pcm, swparams, NFRAMES_VAL);
    error = snd_pcm_sw_params(pcm, swparams);
    if (error) {
	fprintf(stderr, "E: %s\n", snd_strerror(error));
	snd_pcm_close(pcm);
	return NULL;
    }
#endif

    sa->backend_handle = pcm;
    sa->backend_framesize = sa->channels * sa->samplesize; 

    return 1;
}
Exemplo n.º 25
0
bool
play_pcm_buffer (playable_pcm_buffer_t *buffer)
{
  int                 status;
  snd_pcm_t          *handle;
  snd_pcm_format_t    format;
  snd_pcm_sframes_t   frames_wrote;
  int                 frames_count;
  size_t              bytes_handled;
  size_t              bytes_to_write;


  format = determine_pcm_format (&(buffer->info));
  if (format == SND_PCM_FORMAT_UNKNOWN)
    {
      fprintf (stderr, "%s: Unable to determine the beep's PCM data format.\n",
               progname);

      return false;
    }

  status = snd_pcm_open (&handle, "default", SND_PCM_STREAM_PLAYBACK, 0);
  if (status < 0)
    {
      fprintf (stderr, "%s: Failed to open the playback device: %s\n",
               progname, snd_strerror (status));

      return false;
    }

  status = snd_pcm_set_params (handle, format, SND_PCM_ACCESS_RW_INTERLEAVED,
                               buffer->info.channels, buffer->info.sample_rate,
                               1,          /* soft_resample */
                               0);         /* latency (us).*/
  if (status < 0)
    {
      fprintf (stderr, "%s: Failed to configure the playback device: %s.\n",
               progname, snd_strerror (status));

      snd_pcm_close (handle);
      return false;
    }

  bytes_handled = 0;
  while (bytes_handled < buffer->data_len)
    {
      if (buffer->data_len - bytes_handled < BUFSIZ)
        bytes_to_write = buffer->data_len - bytes_handled;
      else
        bytes_to_write = BUFSIZ;

      frames_count = snd_pcm_bytes_to_frames (handle, bytes_to_write);
      frames_wrote = snd_pcm_writei (handle, buffer->data + bytes_handled,
                                     frames_count);
      if (frames_wrote < 0)
        frames_wrote = snd_pcm_recover (handle, frames_wrote, 0);

      if (frames_wrote < 0)
        {
          fprintf (stderr, "%s: Writing to the playback device failed: %s.\n",
                   progname, snd_strerror (frames_wrote));

          snd_pcm_close (handle);
          return false;
        }

      if (frames_wrote > 0 && frames_wrote < frames_count)
        {
          fprintf (stderr, "%s: Warning: Wrote only %ld frames instead of the "
                   "expected %d to the playback device.\n",
                   progname, frames_wrote, frames_count);
        }

      bytes_handled += bytes_to_write;
    }

  snd_pcm_drain (handle);
  snd_pcm_close (handle);

  return true;
}
Exemplo n.º 26
0
bool
play_pcm_file (playable_pcm_file_t *file)
{
  int                 status;
  snd_pcm_t          *handle;
  snd_pcm_format_t    format;
  snd_pcm_sframes_t   frames_wrote;
  uint8_t             playback_buf[BUFSIZ];
  int                 frames_count;
  size_t              read_bytes;


  format = determine_pcm_format (&(file->info));
  if (format == SND_PCM_FORMAT_UNKNOWN)
    {
      fprintf (stderr, "%s: Unable to determine the beep's PCM data format.\n",
               progname);

      return false;
    }

  if (fsetpos (file->stream, &(file->pcm_start_pos)) != 0)
    {
      fprintf (stderr, "%s: Failed to seek to the PCM data of `%s': %s.\n",
               progname, file->name, strerror (errno));

      return false;
    }

  status = snd_pcm_open (&handle, "default", SND_PCM_STREAM_PLAYBACK, 0);
  if (status < 0)
    {
      fprintf (stderr, "%s: Failed to open the playback device: %s\n",
               progname, snd_strerror (status));

      return false;
    }

  status = snd_pcm_set_params (handle, format, SND_PCM_ACCESS_RW_INTERLEAVED,
                               file->info.channels, file->info.sample_rate,
                               1,          /* soft_resample */
                               0);         /* latency (us).*/
  if (status < 0)
    {
      fprintf (stderr, "%s: Failed to configure the playback device: %s.\n",
               progname, snd_strerror (status));

      snd_pcm_close (handle);
      return false;
    }

  while (true)
    {
      read_bytes = fread (playback_buf, 1, BUFSIZ, file->stream);
      if (read_bytes == 0)
        {
          if (ferror (file->stream))
            {
              fprintf (stderr, "%s: An error occured while reading from `%s': %s.\n",
                       progname, file->name, strerror (errno));

              snd_pcm_close (handle);
              return false;
            }

          break;
        }
      frames_count = snd_pcm_bytes_to_frames (handle, read_bytes);
      frames_wrote = snd_pcm_writei (handle, playback_buf, frames_count);
      if (frames_wrote < 0)
        frames_wrote = snd_pcm_recover (handle, frames_wrote, 0);

      if (frames_wrote < 0)
        {
          fprintf (stderr, "%s: Writing to the playback device failed: %s.\n",
                   progname, snd_strerror (frames_wrote));

          snd_pcm_close (handle);
          return false;
        }

      if (frames_wrote > 0 && frames_wrote < frames_count)
        {
          fprintf (stderr, "%s: Warning: Wrote only %ld frames instead of the "
                   "expected %d to the playback device.\n",
                   progname, frames_wrote, frames_count);
        }
    }

  snd_pcm_drain (handle);
  snd_pcm_close (handle);

  return true;
}
Exemplo n.º 27
0
int
cubeb_stream_init(cubeb * context, cubeb_stream ** stream, char const * stream_name,
                  cubeb_stream_params stream_params, unsigned int latency,
                  cubeb_data_callback data_callback, cubeb_state_callback state_callback,
                  void * user_ptr)
{
  cubeb_stream * stm;
  int r;
  snd_pcm_format_t format;
  snd_pcm_uframes_t buffer_size;
  snd_pcm_uframes_t period_size;

  assert(context);
  assert(stream);

  if (stream_params.rate < 1 || stream_params.rate > 192000 ||
      stream_params.channels < 1 || stream_params.channels > 32 ||
      latency < 1 || latency > 2000) {
    return CUBEB_ERROR_INVALID_FORMAT;
  }

  switch (stream_params.format) {
  case CUBEB_SAMPLE_S16LE:
    format = SND_PCM_FORMAT_S16_LE;
    break;
  case CUBEB_SAMPLE_S16BE:
    format = SND_PCM_FORMAT_S16_BE;
    break;
  case CUBEB_SAMPLE_FLOAT32LE:
    format = SND_PCM_FORMAT_FLOAT_LE;
    break;
  case CUBEB_SAMPLE_FLOAT32BE:
    format = SND_PCM_FORMAT_FLOAT_BE;
    break;
  default:
    return CUBEB_ERROR_INVALID_FORMAT;
  }

  stm = calloc(1, sizeof(*stm));
  assert(stm);

  stm->context = context;
  stm->data_callback = data_callback;
  stm->state_callback = state_callback;
  stm->user_ptr = user_ptr;
  stm->params = stream_params;

  r = pthread_mutex_init(&stm->lock, NULL);
  assert(r == 0);

  r = pthread_cond_init(&stm->cond, NULL);
  assert(r == 0);

  r = cubeb_locked_pcm_open(&stm->pcm, SND_PCM_STREAM_PLAYBACK);
  if (r < 0) {
    cubeb_stream_destroy(stm);
    return CUBEB_ERROR;
  }

  r = snd_pcm_nonblock(stm->pcm, 1);
  assert(r == 0);

  r = snd_pcm_set_params(stm->pcm, format, SND_PCM_ACCESS_RW_INTERLEAVED,
                         stm->params.channels, stm->params.rate, 1,
                         latency * 1000);
  if (r < 0) {
    /* XXX: return format error if necessary */
    cubeb_stream_destroy(stm);
    return CUBEB_ERROR;
  }

  r = snd_pcm_get_params(stm->pcm, &buffer_size, &period_size);
  assert(r == 0);
  fprintf(stderr, "b=%u p=%u\n", buffer_size, period_size);

  /* set up poll infrastructure */

  stm->n_descriptors = snd_pcm_poll_descriptors_count(stm->pcm);
  assert(stm->n_descriptors > 0);

  stm->descriptors = calloc(stm->n_descriptors, sizeof(*stm->descriptors));
  assert(stm->descriptors);

  r = snd_pcm_poll_descriptors(stm->pcm, stm->descriptors, stm->n_descriptors);
  assert(r == stm->n_descriptors);

  r = snd_pcm_pause(stm->pcm, 1);
#if 0
  assert(r == 0);
#endif

  stm->state = CUBEB_STREAM_STATE_INACTIVE;

  *stream = stm;

  return CUBEB_OK;
}
Exemplo n.º 28
0
int main(void)
{
	int err;
	unsigned int i;
	
	snd_pcm_t *handle_capture;	/* handle of capture */

	snd_pcm_sframes_t frames;
	
	// Open handle of capture
	if((err=snd_pcm_open(&handle_capture, device, SND_PCM_STREAM_CAPTURE, 0)) < 0) {
		printf("Capture open error: %s\n", snd_strerror(err));
		exit(EXIT_FAILURE);
	}
	
	if((err = snd_pcm_set_params(handle_capture,
				     SND_PCM_FORMAT_S16_LE,
				     SND_PCM_ACCESS_RW_INTERLEAVED,
				     1,
				     48000,
				     1,
				     500000)) < 0) {	/* 0.5s */
		printf("Capture open error: %s\n", snd_strerror(err));
		exit(EXIT_FAILURE);
	}
	printf("             ");
	fflush(stdout);
	
	/*
	 * Formula of dB is 20log((Sound Pressure)/P0)
	   Assume that (Sound Pressure/P0) = k * sample value (Linear!),	   
	   and by experiment, we found that k = 0.45255.
	*/
	double k = 0.45255;
	double Pvalue = 0;
	int dB = 0;
	int peak = 0;
	i=0;

	// Capture 
	while(i<50) {
		frames = snd_pcm_readi(handle_capture, buffer, buffer_size);
		if(frames < 0)
			frames = snd_pcm_recover(handle_capture, frames, 0);
		if(frames < 0) {
			printf("snd_pcm_readi failed: %s\n", snd_strerror(err));
		}
		if(frames > 0 && frames < (long)buffer_size)
			printf("Short read (expected %li, wrote %li)\n", (long)buffer_size, frames);

		Pvalue = rms(buffer) * k;
		
		dB = (int)20*log10(Pvalue);
		if(dB > peak)
			peak = dB;
		int j;	
		for(j=0; j<120; j++)
			printf("\b");
		fflush(stdout);
		printf("dB=%d,Peak=%d | ", dB, peak);
    for(j=0; j<dB; j++){
      printf("=");
    }
    for(j=0; j<100-dB; j++){
      printf(" ");
    }
		fflush(stdout);
	}
	printf("\n");
	snd_pcm_close(handle_capture);
	return 0;
}
Exemplo n.º 29
0
int main(int argc, char** argv) {
    if (argc != 1) {
        fprintf(stderr, "usage: %s < input_file\n", argv[0]);
        exit(1);
    }

    snd_pcm_t* pcm = NULL;
    if (snd_pcm_open(&pcm, "default", SND_PCM_STREAM_PLAYBACK, 0) < 0) {
        oops("snd_pcm_open");
    }

    if (snd_pcm_set_params(pcm,
                           SND_PCM_FORMAT_FLOAT_LE,
                           SND_PCM_ACCESS_RW_INTERLEAVED,
                           n_channels,
                           sample_rate,
                           1,
                           sample_rate / 4) < 0) {
        oops("snd_pcm_set_params");
    }

    snd_pcm_uframes_t period_size = 0, buffer_size = 0;
    if (snd_pcm_get_params(pcm, &buffer_size, &period_size) < 0) {
        oops("snd_pcm_get_params");
    }

    printf("period_size = %ld\n", (long)period_size);
    printf("buffer_size = %ld\n", (long)buffer_size);

    const int buf_sz = period_size * n_channels * sizeof(float);
    void* buf = malloc(buf_sz);

    for (;;) {
        memset(buf, 0, buf_sz);

        const ssize_t rd_sz = read(STDIN_FILENO, buf, buf_sz);
        if (rd_sz < 0) {
            oops("read(stdin)");
        }

        if (rd_sz == 0) {
            break;
        }

        int ret = snd_pcm_writei(pcm, buf, period_size);

        if (ret < 0) {
            if ((ret = snd_pcm_recover(pcm, ret, 1)) == 0) {
                printf("recovered after xrun (overrun/underrun)\n");
            }
        }

        if (ret < 0) {
            oops("snd_pcm_writei");
        }
    }

    free(buf);

    snd_pcm_drain(pcm);
    snd_pcm_close(pcm);

    return 0;
}
Exemplo n.º 30
0
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;
}