Android dump数据到文件

void writepcmtofile(const char * fname,const void* buffer, size_t bytes)
{
      static FILE *fp=NULL;
      if(fp==NULL || access( fname, F_OK )==-1){
       fp = fopen(fname, "ab+" );
       if(fp==NULL){
       ALOGI("can't open file!");
                 fp=NULL;
                 return;
       }
   }
      if(fp!=NULL){
          fwrite(buffer , 1 , bytes , fp );
          ALOGI("write to file %d bytes",bytes);
   }
}

注意,File设置为static的目的是为了更快,但是两个地方同时使用这个函数的时候,因为File只有一个,就会有问题。所以应该改成非静态的。

Android录音,播放,dump数据位置:

ssize_t AudioFlinger::PlaybackThread::threadLoop_write() {
... ...
ssize_t framesWritten = mNormalSink->write(
            (char *) mSinkBuffer + offset, count);
writepcmtofile("/data/test/play.pcm",(int8_t *)inShort, lengthIn * 2);
}
bool AudioFlinger::RecordThread::threadLoop() {
    if (mPipeSource != 0) {
        ......
        }
        // otherwise use the HAL / AudioStreamIn directly
    } else {
        ssize_t bytesRead = mInput->stream->read(mInput->stream,
                (uint8_t*) mRsmpInBuffer + rear * mFrameSize, mBufferSize);
        writepcmtofile("/data/test/clean.pcm",(uint8_t*) mRsmpInBuffer + rear * mFrameSize, bytesRead);
}

如果写不成功,很可能是因为seLinux,这时候写到/user/data下,并设置
adb shell setenforce 0

Java里面的写法:

public static void writeToFile(byte[] mBuffer, String filename, boolean encoded, int quality) {
if (Dbg.isVerbose() || true) {
    try {
        boolean logDirExists;
        String folder = Dbg.LOG_DIR;
        if (!folder.endsWith(File.separator)) {
            folder += File.separatorChar;
        }
        File f = new File(folder);
        if (!f.exists()) {
            logDirExists = f.mkdirs();
        } else {
            logDirExists = true;
        }
        if (!logDirExists) {
            return;
        }
        String path = folder + filename;
        if (encoded) {
            path += "_q" + quality + ".speex";
        } else {
            path += ".pcm";
        }
        File file = new File(path);
        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream stream = new FileOutputStream(file.getAbsoluteFile(), true);
        try {
            stream.write(mBuffer);
        } finally {
            stream.close();
        }
    } catch (IOException e) {
        Log.e("Audio Dump", "Exception", e);
    }
}
}

你可能感兴趣的:(工程实践)