⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sound.c

📁 其中sound.c 用于录音和回放。其中特别需要注意的是:1。目前声卡似乎不能打开全双工
💻 C
字号:
/*
 * sound.c
 */
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <stdio.h>
#include <linux/soundcard.h>

#define LENGTH 10    /* 存储秒数 */
#define RATE 8000   /* 采样频率 */		
#define SIZE 16      /* 量化位数 */
#define CHANNELS 1  /* 声道数目 */

/* 用于保存数字音频数据的内存缓冲区 */
unsigned char buf[LENGTH*RATE*SIZE*(CHANNELS+1)/8];

int main()
{
  int fd; /* 声音设备的文件描述符 */
  int fd_r;
  int fd_w;
  int waveid; /*保存wav声音文件描述符 */
  int arg; /* 用于ioctl调用的参数 */
  int status;   /* 系统调用的返回值 */

  /* 打开声音设备 */
  fd = open("/dev/dsp", O_RDWR);
  if (fd < 0) {
    perror("open of /dev/dsp failed");
    exit(1);
  }
  
 /* waveid = open("test.wav",O_RDWR);
  if (waveid < 0) {
  	perror("open test.wav failed");
  	exit(1);
  } */

  /* 设置采样时的量化位数 */
  arg = SIZE;
  status = ioctl(fd, SOUND_PCM_WRITE_BITS, &arg);
  if (status == -1)
    perror("SOUND_PCM_WRITE_BITS ioctl failed");
  if (arg != SIZE)
    perror("unable to set sample size");

  /* 设置采样时的声道数目 */
  arg = CHANNELS; 
  status = ioctl(fd, SOUND_PCM_WRITE_CHANNELS, &arg);
  if (status == -1)
    perror("SOUND_PCM_WRITE_CHANNELS ioctl failed");
  if (arg != CHANNELS)
    perror("unable to set number of channels");

  /* 设置采样时的采样频率 */
  arg = RATE;
  status = ioctl(fd, SOUND_PCM_WRITE_RATE, &arg);
  if (status == -1)
  	 perror("SOUND_PCM_WRITE_WRITE ioctl failed");
    
  close(fd);                            /*关闭声卡*/


  /* 循环,直到按下Control-C */
  while (1) {
  	
  	fd_r = open("/dev/dsp", O_RDONLY);
  	if (fd_r < 0) {
    	perror("open of /dev/dsp failed");
    	exit(1);
 		}
    printf("Say something:\n");
    status = read(fd_r, buf, sizeof(buf)); /* 录音 */
    if (status != sizeof(buf))
      perror("read wrong number of bytes");
		
		close(fd_r);
		
		printf("Press any key to playback:\n");
    getchar();

  	fd_w = open("/dev/dsp", O_WRONLY);
  	if (fd_r < 0) {
    	perror("open of /dev/dsp failed");
    	exit(1);
 		}
    printf("You said:\n");
    status = write(fd_w, buf, sizeof(buf)); /* 回放 */
    if (status != sizeof(buf))
       perror("wrote wrong number of bytes");

    /* 在继续录音前等待回放结束 */
    status = ioctl(fd_w, SOUND_PCM_SYNC, 0); 
    if (status == -1)
       perror("SOUND_PCM_SYNC ioctl failed");
      
    printf("Press any key to go again:\n");
    getchar(); 
    
    close(fd_w);
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -