/*

Example 333 - Very Simple sound playback

This example reads standard from input and writes
to the default PCM device 

*/

/* Use the standard ALSA API */

#include <alsa/asoundlib.h>


  snd_pcm_t *alsahandle;
  snd_pcm_uframes_t frames;

  char *buffer;

void init() {
int rc;
int dir;
int val;

/* Open PCM device for playback. */
rc = snd_pcm_open(&alsahandle, "default", SND_PCM_STREAM_PLAYBACK, 0);
if (rc < 0) {
    fprintf(stderr, "unable to open pcm device: %s\n", snd_strerror(rc));
    exit(1);
 }

/* Set parameters for playback */
rc = snd_pcm_set_params(alsahandle,                       /* snd PCM handle */
                        SND_PCM_FORMAT_S16_BE,		  /* data format */
                        SND_PCM_ACCESS_RW_INTERLEAVED,    /* data access */
                         2,				  /* channels    */
                         41000,                           /* sampling rate */
                         1,                               /* soft resample */
                         256);				  /* latency      */


  if (rc < 0) {
    fprintf(stderr, "unable to set alsa parameters: %s\n", snd_strerror(rc));
    return -1;
   }
}

void suona(int fd) {
int rc;
int size;
int dir;

 /* Use a buffer large enough to hold one period */
  frames=16;
  size = frames * 4; /* 2 bytes/sample, 2 channels */
  buffer = (char *) malloc(size);
 rc=1;
  while (rc!=0) {
    rc = read(fd, buffer, size);
    if (rc == 0) {
      fprintf(stderr, "end of file on input\n");
      break;
    } else if (rc != size) {
      fprintf(stderr, "short read: read %d bytes\n", rc);
    }
    rc = snd_pcm_writei(alsahandle, buffer, frames);
    if (rc == -EPIPE) {
      /* EPIPE means underrun */
      fprintf(stderr, "underrun occurred\n");
      snd_pcm_prepare(alsahandle);
    } else if (rc < 0) {
      fprintf(stderr, "error from writei: %s\n", snd_strerror(rc));
    }  else if (rc != (int)frames) {
      fprintf(stderr, "short write, write %d frames\n", rc);
    }
  }
 
}

int main() {

int fd;

init() ; 
fd=open("audio_02.cdr",O_RDONLY);
suona(fd);
close(fd);
snd_pcm_drain(alsahandle);
snd_pcm_close(alsahandle);
free(buffer);
  
return 0;
}
