ossdevice.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // ossdevice.cpp
  2. #ifdef __linux
  3. #include "freeaudio.h"
  4. #include <sys/ioctl.h>
  5. #include <unistd.h>
  6. #include <fcntl.h>
  7. #include <sys/soundcard.h>
  8. #include <pthread.h>
  9. extern "C" audiodevice *OpenOSSDevice();
  10. void *ossaudiothread(void*dev);
  11. #define LINUXFRAG 2048
  12. void *ossaudiothread(void *arg);
  13. struct ossdevice:audiodevice{
  14. pthread_t audiothread;
  15. int threadid;
  16. int running,playing;
  17. short *buffer;
  18. int buffersize; //in bytes
  19. int fragsize,fragcount;
  20. int fd,data,res;
  21. int reset(){
  22. running=0;
  23. playing=0;
  24. fd=open("/dev/dsp",O_WRONLY,0);
  25. if (fd==-1) return -1;
  26. mix=new mixer(LINUXFRAG);
  27. mix->freq=44100;
  28. mix->channels=2;
  29. buffer=new short[LINUXFRAG];
  30. buffersize=LINUXFRAG*2;
  31. pthread_attr_t attr;
  32. pthread_attr_init(&attr);
  33. running=1;
  34. threadid=pthread_create(&audiothread,&attr,ossaudiothread,(void*)this);
  35. return 0;
  36. }
  37. int close(){
  38. int timeout;
  39. running=0;
  40. timeout=500;
  41. while (timeout-- && playing) usleep( 10*1000 );
  42. ::close(fd);
  43. return 0;
  44. }
  45. void run(){
  46. // printf("linuxaudio started\n");
  47. data=0x03000c; //2 fragments of 4096 samples
  48. res=ioctl(fd,SNDCTL_DSP_SETFRAGMENT,&data);
  49. // printf("res=%d\n",res);
  50. data=AFMT_S16_LE;
  51. res=ioctl(fd,SNDCTL_DSP_SETFMT,&data);
  52. // printf("res=%d\n",res);
  53. data=2;
  54. res=ioctl(fd,SNDCTL_DSP_CHANNELS,&data);
  55. // printf("res=%d\n",res);
  56. data=44100;
  57. res=ioctl(fd,SNDCTL_DSP_SPEED,&data);
  58. playing=1;
  59. while (playing && running){
  60. mix->mix16(buffer);
  61. int n=write(fd,buffer,buffersize);
  62. }
  63. playing=0;
  64. }
  65. };
  66. void *ossaudiothread(void *arg){
  67. ossdevice*audio=(ossdevice*)arg;
  68. audio->run();
  69. return 0;
  70. }
  71. audiodevice *OpenOSSDevice(){
  72. return new ossdevice();
  73. }
  74. #endif