My Ioctl Soundring Buffer


rlyeh

Certified Guru
Joined
Mar 25, 2003
Messages
277
Age
45
Location
49°9' East latitude, 126°43' South longitude: in y
Website
www.retrodev.info
Here you have what i've been coding yesterday night
My crystal clear soundring buffer using ioctl()

You have to supply and call periodically sound_frame() (in each finished frame)
Maybe someone would rather like to hang it up in a thread?

Hope you like it...
Feedback is welcome :)

PS: This code is not exactly the same I wrote yesterday, as mine it's HPL based. I've converted it to C directly while I was posting this thread. Please tell me if it does not work at all O:)


Code:
extern void sound_frame(void *blah, void *bufferg, int samples);

#define SOUND_DEVICE            "/dev/dsp"
#define SOUND_DEVICE_BUFFSIZE   (44100/60)
int sound_fd=0, sound_numsamples,sound_samplesize;
signed short sound_fd_buffer[SOUND_DEVICE_BUFFSIZE*4];

int sound_open(int rate, int bits, int stereo)
{
  int tmp;

  if ( sound_fd ) { close(sound_fd); sound_fd=0; }

  /* Open sound device */
  if ( (sound_fd = open( SOUND_DEVICE, O_WRONLY )) < 0 )
   return (sound_fd = 0);
  
  /* Setting signed 16-bit format */ 
  tmp = (bits == 16 ? AFMT_S16_LE : AFMT_U8);
  if ( ioctl(sound_fd, SNDCTL_DSP_SETFMT, &tmp) < 0 )
    { close(sound_fd); return (sound_fd = 0); }

  /* Setting stereo mode */
//  tmp = stereo+1;
//  if ( ioctl(sound_fd, SNDCTL_DSP_CHANNELS, &tmp) < 0 )

  tmp = stereo; 
  if ( ioctl(sound_fd, SNDCTL_DSP_STEREO, &tmp) < 0 )
    { close(sound_fd); return (sound_fd = 0); }
    
  /* Setting sample rate */
  tmp = rate;
  if ( ioctl(sound_fd, SNDCTL_DSP_SPEED, &tmp) < 0 )
    { close(sound_fd); return (sound_fd = 0); }

  sound_numsamples=(SOUND_DEVICE_BUFFSIZE)/(44100/rate);
  sound_samplesize=sound_numsamples << (stereo + (bits==16));

  /* Successful */
  return 1;
}


void sound_close(void)
{
  if ( sound_fd ) close(sound_fd);
}


void sound_play(void)
{
  if( sound_fd ) 
  {
    sound_frame(NULL, &sound_fd_buffer[0], sound_numsamples);
    write( sound_fd, &sound_fd_buffer[0], sound_samplesize);
  }
}

/* now supply your own function for 16 bits, stereo:

    void sound_frame(void *blah, void *bufferg, int samples)
    {
      signed short *buffer=(signed short *)bufferg;
      while(samples--)
      {
        *buffer++=0; //Left channel
        *buffer++=0; //Right channel
      }
    }

   or for 8 bits, mono:

    void sound_frame(void *blah, void *bufferg, int samples)
    {
      unsigned char *buffer=(unsigned char *)bufferg;
      while(samples--)
      {
        *buffer++=0; //Central channel
      }
    }

    etc...
*/
 
Back
Top