Feedback

C++ - Audioaufzeichnung unter Linux

Veröffentlicht von am 7/11/2008
(1 Bewertungen)
Zeichnet in Linux ein Audiosignal vom Standard-Audioinput auf, speicher es in einen char-Puffer und spielt es anschließend wieder ab

Quelle: http://www.c-plusplus.de/forum/viewtopic-var-t-is-217635.html
using namespace std; 

#define CHANNELS  1 
#define RATE      16000  // sampling rate! 
#define AFMT      AFMT_S16_LE 
#define FRAG      0x7fff000b 

static int fd; 

int openAudio(int mode) 
{ 
    int mask; 
    int channelsT = CHANNELS; 
    int rateT     = RATE; 
    int afmtT     = AFMT; 
    int frag      = FRAG; 

    /***** open audio device /dev/dsp*/ 

    if ((fd = open("/dev/dsp", mode, 0)) == -1) 
    { 
        return(-1); 
    } 

    /***** check whether 16 bit recording is possible on the current sound hardware */ 

    if (ioctl(fd, SNDCTL_DSP_GETFMTS, &mask) == -1) 
    { 
        return(-1); 
    } 
  
    if (!(mask & AFMT)) 
    { 
        return(-1); 
    } 

    /***** set audio recording to 16kHz, 16bit, mono */ 

    if (ioctl(fd, SNDCTL_DSP_SETFMT, &afmtT)      == -1 || 
        afmtT != AFMT                                   || 
        ioctl(fd, SNDCTL_DSP_CHANNELS, &channelsT)== -1 || 
        channelsT != CHANNELS                           || 
        ioctl(fd, SNDCTL_DSP_SPEED, &rateT)       == -1 || 
        rateT != RATE                                   || 
        ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &frag)  == -1) 
    { 
        return(-1); 
    } 

    return(1); 
} 

int closeAudio() 
{   
    close(fd);   
    return(1); 
} 

int playUtterance(unsigned char *wav, long length) 
{ 
    fprintf(stderr, "I write %d bytes\n",length); 
    write(fd, wav, length); 
    return(1); 
} 

unsigned char *getUtterance(long length) 
{ 
    int i;int n;int retval; 
    unsigned char * buffer_raw; 
    buffer_raw =(unsigned char *) malloc(sizeof(unsigned char)*length); 
  
    memset (buffer_raw, 0x00, length); 

    fprintf(stderr, "I read %d bytes\n",length); 
    if ((retval = read(fd, buffer_raw, length)) == -1) 
    { 
        return NULL; 
    } 
    fprintf(stderr, "I got %d bytes\n",retval); 
    return buffer_raw; 
} 


int main() 
{ 
    unsigned char * buffer; 
    // read 
    if (openAudio( O_RDONLY) > 0) { 
        fprintf(stderr, "audio opened.\n"); 
    } 
    long nb = 128000; // number of bytes to read... 
    buffer = getUtterance(nb); 
    closeAudio(); 
    if (openAudio(O_WRONLY) > 0) { 
        fprintf(stderr, "audio opened.\n"); 
    } 
    playUtterance(buffer, nb ); 
    closeAudio(); 
    return 0; 
} 
Abgelegt unter Audio, Linux.

Kommentare zum Snippet

 

Logge dich ein, um hier zu kommentieren!