Linux下的音频采集与回放


  作者: hotfire [文章出自: www.PHPx.com]

以下假设你对ioctl已有一定的认识及了解

sndtools.h

代码:
#ifndef SNDTOOLS_H
#define SNDTOOLS_H

#include <Linux/soundcard.h>

#define FMT8BITS AFMT_S8_LE
#define FMT16BITS AFMT_S16_LE

#define FMT8K 8000
#define FMT16K 16000
#define FMT22K 22000
#define FMT44K 44000

#define MONO 1
#define STERO 2

#ifndef VAR_STATIC
extern int devfd;
extern int CapMask;
#endif //ifndef VAR_STATIC

//Open sound device, return 1 if open sUCcess
//else return 0
int OpenSnd();

//Close sound device
int CloseSnd();

//Set record or playback format, return 1 if success
//else return 0
int SetFormat(int bits, int hz);

//Set record or playback channel, return 1 if success
//else return 1
int SetChannel(int chn);

//Record
int Record(char *buf, int size);

//Playback
int Play(char *buf, int size);

#endif //ifndef SNDTOOLS_H



sndtools.c

代码:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <string.h>

#define VAR_STATIC

#include "sndtools.h"

int devfd = 0;

/*
* Open Sound device
* Return 1 if success, else return 0.
*/
int OpenSnd(/* add by new version */int nWhich)
{
if(devfd > 0)
close(devfd);

devfd = open("/dev/dsp", O_RDWR);

if(devfd < 0)
return 0;
return 1;
}

/*
* Close Sound device
* return 1 if success, else return 0.
*/
int CloseSnd(/* add by new version */int nWhich)
{
close(devfd);
devfd = 0;
return 1;
}


/*
* Set Record an Playback format
* return 1 if success, else return 0.
* bits -- FMT8BITS(8bits), FMT16BITS(16bits)
* hz -- FMT8K(8000HZ), FMT16K(16000HZ), FMT22K(22000HZ), FMT44K(44000HZ)
*/
int SetFormat(int bits, int hz)
{
int tmp = bits;

if( -1 == ioctl(devfd, SNDCTL_DSP_SETFMT, &tmp))
{

#ifdef DEBUG_WARN
printf("Set fmt to s16_little faile:%d\\n", nWhich);
#endif

return 0;
}

tmp = hz;
if( -1 == ioctl(devfd, SNDCTL_DSP_SPEED, &tmp))

共2 页 首页 上一页 [1] [2下一页 尾页>