ALSA Dump to File


Cheat sheet to save audio data to files. Useful for dumping audio from flash, games, …

Tool to save data to timestamped files:

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <fcntl.h>
#include <time.h>
#define BUFFLEN 1024

int main(int argc, char **argv)
{
        int fd;
        int bytes_read;
        char buff[BUFFLEN];
        char fname[BUFFLEN];
        time_t datetime;
        datetime = time(NULL);
        sprintf(fname, "/tmp/%ld.raw", datetime);
        if((fd = open(fname, O_CREAT | O_WRONLY, S_IRUSR| S_IWUSR)) == -1) {
                perror("Failed to open file for writing");
                return(1);
        }
        while((bytes_read = read(0, buff, BUFFLEN))) {
                write(fd, buff, bytes_read);
        }
        close(fd);
        return(0);
}

Save to a file /home/user/tmp/save_to_file.c
Compile: gcc save_to_file.c -o save_to_file

Config file to have alsa copy the sound stream to files:

defaults.pcm.file_truncate false
pcm.!default {
type plug
slave { pcm "tee:hw,|/home/user/tmp/save_to_file" }
}

Save to /home/user/.asoundrc
Start the app to produce the sounds. One file will be generated every time the app opens the soud device.

The output files are raw PCM audio.

Play with:
aplay -f cd /tmp/123456789.raw

Conversion to vorbis:
cd /tmp
oggenc -r -q 7 *.raw

Conversion to mp3 should be something like:
lame -r -s 44.1 –signed –little-endian -h -V 2 /tmp/123456789.raw
but for some reason it only produces noise for me.

© 2010 r@hq.sk
Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.


Leave a Reply

Your email address will not be published. Required fields are marked *