Pages

Get it free, Try now

Free Cell Phones

Tuesday, December 14, 2010

Android - Accessing Input device "msm_pcm_in" from User space

This article shows code snippet on how to access input device driver from user space.

Recording from input device (msm_pcm_in: a char Device Driver) follows the below events

Open device :

int ret = open("/dev/msm_pcm_in", O_RDWR); // open device

struct msm_audio_config confg;

ioctl(ret, AUDIO_GET_CONFIG, &confg) // this call fill the structure with default driver values.


cfg.channel_count = 1; // assign new number of channel(1= mono, 2 = stereo)
cfg.sample_rate = 8000;// assign sampling rate such as 8000 or 16000,.....
int val = ioctl(ret, AUDIO_SET_CONFIG, &confg);// set the new audio configuration


Before we being to start audio read/write operations, create a file to store buffers
const char *fn = /sdcard/tmp/file1;
int file = open(fn, O_CREAT | O_RDWR, 0666);

bool isrecording = true; // use this flag to stop recording (true default, false to disable reading)

ioctl(ret, AUDIO_START, 0);





fcntl(0, F_SETFL, O_NONBLOCK);// provides control of open file descriptors.

unsigned char buf[4092];

for (;;) {
while (!isrecording) {
// close all file descriptors and exit
}
if (read(ret, buf,confg.buffer_size ) != confg.buffer_size) {
// if fail to read
// close all file descriptors and exit
}

if (write(file, buf, confg.buffer_size) != confg.buffer_size) {
// if fail to read
// close all file descriptors and exit
}

}




Close device:


close(ret);
...
...
close (file);



Note: To run this as a recorder app, make sure you have root privileges.

6 comments:

  1. Can this code be compiled in conjunction with the NDK or does this have to be included with the Android open source code?

    ReplyDelete
  2. Yes, you can compile this as a lib or exe, not necessary to include in AOSP but only constraint is that you need to be root to access the device from user space. I have tested this on rooted device and worked like a charm.

    ReplyDelete
  3. Would this be possible for msm_pcm_out instead of msm_pcm_in?

    ReplyDelete
  4. So I got the program working but when I pull the file it says it is a text file. What do I need to do in order to play what I recorded?

    ReplyDelete
  5. Recheck the recorded format and try playing through msm_pcm_out or any other player.

    ReplyDelete
  6. This is useful because I´m on a tri I need to get this done. In this apartment in buenos aires I´m satying in I have a computer they gave me which works great but I wanted to know how to do this.
    Thanks!
    Kim

    ReplyDelete