?? testaudio.c
字號:
//
// Description
// Record and play sound
//
// Copyright (C) 2004 Hyesco Technology Co.,Ltd
//
// Author: Zheng Geng <gzheng@hyesco.com>
//
// History:
//
// 2004.8 Zheng Geng <gzheng@hyesco.com>
// Original version
//
#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 5 /* 存儲秒數(shù) */
#define RATE 44100 /* 采樣頻率 */
#define SIZE 16 /* 量化位數(shù) */
#define CHANNELS 1 /* 聲道數(shù)目 */
/* 用于保存數(shù)字音頻數(shù)據(jù)的內(nèi)存緩沖區(qū) */
unsigned char buf[LENGTH*RATE*SIZE*CHANNELS/8];
unsigned char tempbuf[LENGTH*RATE*SIZE*CHANNELS/8];
int main()
{
int fd;
int arg,i,n; /* 用于ioctl調(diào)用的參數(shù) */
int status; /* 系統(tǒng)調(diào)用的返回值 */
// 打開聲音設(shè)備
fd = open("/dev/sound/dsp", O_RDWR);
if (fd < 0)
{
perror("open of /dev/dsp failed");
exit(1);
}
// 設(shè)置采樣時(shí)的量化位數(shù)
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");
// 設(shè)置采樣時(shí)的聲道數(shù)目
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");
//設(shè)置采樣時(shí)的采樣頻率
arg = RATE;
status = ioctl(fd, SOUND_PCM_WRITE_RATE, &arg);
if (status == -1)
perror("SOUND_PCM_WRITE_WRITE ioctl failed");
//循環(huán),直到按下Control-C
n=RATE*SIZE*CHANNELS/8;
while (1)
{
memset(buf, 0, sizeof(buf));
printf("Say something:\n");
for (i=0;i<LENGTH;i++)
{
status = read(fd, tempbuf, n); // 錄音1秒
if (status != n)
perror("read wrong number of bytes");
memcpy(buf+i*n,tempbuf,n);
}
printf("You said:\n");
status = write(fd, buf, sizeof(buf)); // 回放
if (status != sizeof(buf))
perror("wrote wrong number of bytes");
// 在繼續(xù)錄音前等待回放結(jié)束
status = ioctl(fd, SOUND_PCM_SYNC, 0);
if (status == -1)
perror("SOUND_PCM_SYNC ioctl failed");
getchar();
}
close(fd);
return 0;
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -