[alsa-devel] How to play a pcm file

Flávio Yuiti f_yuiti at yahoo.com.br
Thu Apr 26 02:51:14 CEST 2007


Greetings,
   
  I'm a new user of alsa api and I need to play pcm, adpcm and wav files using Alsa api. My code is below. I did a test with pcm file and the sound is playing very fast, the properties of the pcm file are 128kbps, 16 bits little endian, 1 channel, 8 khz, but I don't know how to set correctly the parameters in api. Please help me with this problem. Point me my errors.
   
  Thanks,
   
  Flavio
   
  int Sound::PlayFile(char *pszFileName, ULONG initialPoint, UINT qtdTimesToPlay, BOOL mix)
  {
  int dir;
  int result;
  int size;
  unsigned int val;
  snd_pcm_hw_params_t *params;
  snd_pcm_uframes_t frames;
  char* buffer;
  long tamanhoBuffer;
  FILE* file;
  int bytesLidos;
   
  // Open PCM device for playback.
  if((result = snd_pcm_open(&handleSound,"hw:0,0",SND_PCM_STREAM_PLAYBACK,0)) < 0)
  {
  fprintf(stderr,"\nUnable to open pcm device: %s",snd_strerror(result));
  exit(1);
  }
  
  // Allocate a hardware parameters object.
  snd_pcm_hw_params_alloca(&hardwareParam);
  // Fill it in with default values.
  snd_pcm_hw_params_any(handleSound,hardwareParam);
  // Set the desired hardware parameters.
  // Interleaved mode.
  snd_pcm_hw_params_set_access(handleSound,hardwareParam,SND_PCM_ACCESS_RW_INTERLEAVED);
  // Signed 16-bit little-endian format.
  snd_pcm_hw_params_set_format(handleSound,hardwareParam,SND_PCM_FORMAT_S16_LE);
  // Two channels (stereo), one channel mono.
  snd_pcm_hw_params_set_channels(handleSound,hardwareParam,1);
  // Set rate.
  //snd_pcm_hw_params_set_rate(handleSound,hardwareParam,8000,0);
  // Set period size to 16384 frames.
  //snd_pcm_hw_params_set_period_size(handleSound,hardwareParam,16384,0);
  // Write the parameters to the driver.
  if((result = snd_pcm_hw_params(handleSound,hardwareParam)) < 0)
  {
  fprintf(stderr,"\nUnable to set hw parameters: %s",snd_strerror(result));
  exit(1);
  }
  
  tamanhoBuffer = 16384;
  if((result = snd_pcm_prepare(handleSound)) < 0)
  {
  fprintf(stderr,"Cannot prepare audio interface for use: %s\n",snd_strerror(result));
  exit(1);
  }
  file = fopen(pszFileName,"rb");
  buffer = (char *)malloc(tamanhoBuffer);
  while((bytesLidos = fread(buffer,1,tamanhoBuffer,file)) > 0)
  {
  if((result = snd_pcm_writei(handleSound,buffer,tamanhoBuffer)) != tamanhoBuffer)
  {
  fprintf(stderr,"Write to audio interface failed: %s\n",snd_strerror(result));
  exit(1);
  }
  }
  
  snd_pcm_drain(handleSound);
  snd_pcm_close(handleSound);
  free(buffer);
  fclose(file);
  
  
  return OK;
  }

 __________________________________________________
Fale com seus amigos  de graça com o novo Yahoo! Messenger 
http://br.messenger.yahoo.com/ 


More information about the Alsa-devel mailing list