从FileDescriptor读取流字节

时间:2018-10-29 09:55:35

标签: android stream

我是android和java的初学者。

但是,我想使用MediaRecorder录制语音并获取记录为byte []的数据,我编写了以下代码:

ParcelFileDescriptor[] fileDescriptors = ParcelFileDescriptor.createPipe();
ParcelFileDescriptor readFD = fileDescriptors[0];
ParcelFileDescriptor writeFD = fileDescriptors[1];
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(writeFD.getFileDescriptor());
recorder.setMaxDuration(6000);
recorder.prepare();
recorder.start();

    recorder.setOnErrorListener(new MediaRecorder.OnErrorListener() {
        @Override
        public void onError(MediaRecorder mediaRecorder, int i, int i1) {
            mediaRecorder.stop();
            Log.d("voice", "onError");
            mediaRecorder.release();
        }
    });
    recorder.setOnInfoListener(new MediaRecorder.OnInfoListener() {
        @Override
        public void onInfo(MediaRecorder mediaRecorder, int i, int i1) {
            mediaRecorder.stop();
            Log.d("voice", "onInfo");
            mediaRecorder.release();
        }
    });

    InputStream inputStream = new ParcelFileDescriptor.AutoCloseInputStream(readFD);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();


    int read = -1;
    byte[] data = new byte[4000];


    while ((read = inputStream.read(data, 0, data.length))  != -1) {
         byteArrayOutputStream.write(data, 0, read);
    }

    byte[] byteResult = byteArrayOutputStream.toByteArray();
    byteArrayOutputStream.flush();
    byteArrayOutputStream.close();
 return byteResult;

我对此有很大的疑问,我调试了代码,当我到达这一行时:

while ((read = inputStream.read(data, 0, data.length))  != -1) {
         byteArrayOutputStream.write(data, 0, read);
    }

过了一会儿,android studio向我显示消息并说:“应用程序正在运行”,我不得不停止它。...

任何人都可以帮助我,告诉我代码有什么错误吗?

1 个答案:

答案 0 :(得分:1)

您可以使用此功能available()

while ((inputStream.read(data, 0, data.length))  != -1) {
     read = inputStream.read(data, 0, data.length);
     byteArrayOutputStream.write(data, 0, read);
}