Login
Immutable PageDiscussionInfoAttachments
attachment:sound1.c of mernao/hyakuman2013spring

MMA

Attachment 'sound1.c'

Download

   1 #include <fcntl.h>
   2 #include <limits.h>
   3 #include <linux/soundcard.h>
   4 #include <math.h>
   5 #include <stdio.h>
   6 #include <sys/ioctl.h>
   7 #include <unistd.h>
   8 
   9 #define BUFSIZE 441000
  10 
  11 static int setup_dsp( int fd );
  12 
  13 int 
  14 main( void )
  15 {
  16   double total = 5.0, t; // バッファは5秒
  17   double freq_l = 6000; // 左チャンネルの周波数
  18   double freq_r = 5000; // 右チャンネルの周波数
  19   
  20   short  buf[ 2*BUFSIZE / sizeof(short) ];
  21   int    fd, i;
  22   
  23   
  24   if ( ( fd = open( "/dev/dsp", O_WRONLY ) ) == -1 ) {
  25     perror( "open()" );
  26     return 1;
  27   }
  28   
  29   
  30   /* /dev/dsp の設定 */
  31   if ( setup_dsp( fd ) != 0 ) {
  32     fprintf( stderr, "Setup /dev/dsp failed.\n" );
  33     close( fd );
  34     return 1;
  35   }
  36    
  37   /* 再生用の正弦波データ作成 */
  38   for ( i = 0; i < BUFSIZE / sizeof(short); i ++ ) {
  39     t = ( total / (BUFSIZE / sizeof(short)) ) * i;
  40     buf[2*i] = SHRT_MAX * sin( 2.0 * 3.14159 * freq_l * t );
  41     buf[2*i+1] = SHRT_MAX * sin( 2.0 * 3.14159 * freq_r * t );
  42   }
  43     
  44   // バッファを/dev/dspに書き込み
  45   for(;;){
  46     if ( write( fd, buf, BUFSIZE ) == -1 ) {
  47       perror( "write()" );
  48       close( fd );
  49       return 1;
  50     }
  51   }
  52   close( fd );
  53   return 0;
  54 }
  55 
  56 
  57 static int
  58 setup_dsp( int fd )
  59 {
  60 	int fmt     = AFMT_S16_LE;
  61 	int freq    = 44100;
  62 	int channel = 2; // 2chステレオに設定
  63 
  64 	/* サウンドフォーマットの設定 */
  65 	if ( ioctl( fd, SOUND_PCM_SETFMT, &fmt ) == -1 ) {
  66 		perror( "ioctl( SOUND_PCM_SETFMT )" );
  67 		return -1;
  68 	}
  69 
  70 	/* チャンネル数の設定 */
  71 	if ( ioctl( fd, SOUND_PCM_WRITE_CHANNELS, &channel ) == -1 ) {
  72 		perror( "iotcl( SOUND_PCM_WRITE_CHANNELS )" );
  73 		return -1;
  74 	}
  75 
  76 	/* サンプリング周波数の設定 */
  77 	if ( ioctl( fd, SOUND_PCM_WRITE_RATE, &freq ) == -1 ) {
  78 		perror( "iotcl( SOUND_PCM_WRITE_RATE )" );
  79 		return -1;
  80 	}
  81 
  82 	return 0;
  83 }

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.
  • [get | view] (2021-03-03 17:31:20, 1.8 KB) [[attachment:sound1.c]]
  • [get | view] (2021-03-03 17:31:20, 1.8 KB) [[attachment:sound2.c]]
  • [get | view] (2021-03-03 17:31:20, 1.8 KB) [[attachment:sound3.c]]
  • [get | view] (2021-03-03 17:31:20, 1.8 KB) [[attachment:sound4.c]]
  • [get | view] (2021-03-03 17:31:20, 2.1 KB) [[attachment:sound5.c]]
  • [get | view] (2021-03-03 17:31:20, 2.5 KB) [[attachment:sound6.c]]
 All files | Selected Files: delete move to page copy to page

You are not allowed to attach a file to this page.