Android将数据从ByteBuffer存储到存储

时间:2017-08-23 05:12:48

标签: android streaming bytebuffer android-broadcastreceiver

我使用第三方sdk广播流,在添加回调后,我成功获得了ByteBuffer音频,但是当我将其保存到sdcard无法播放时

这是我的代码片段

    long startedTime = -1;

    @Override
    public void onAudioBuffer(ByteBuffer byteBuffer, int i, long l) {
        if (bufferedOutputStream == null)
            createFile();
        Log.e(TAG, "i:" + i);
        Log.e(TAG, "l:" + l);
        Log.e(TAG, "byteBuffer capacity:" + byteBuffer.capacity());
        Log.e(TAG, "byteBuffer length:" + byteBuffer.array().length);
        if (startedTime == -1) {
            startedTime = System.currentTimeMillis();
            createFile();
        } else if (System.currentTimeMillis() - startedTime > 10000) {
            try {
                bufferedOutputStream.close();
                startedTime = -1;
            } catch (IOException e) {
                Log.e(TAG, "byteBuffer bufferedOutputStream closing err:" + e.getMessage());
                e.printStackTrace();
            }
            return;
        } else {
            try {
                byte[] bytes = new byte[byteBuffer.capacity()];
                byteBuffer.get(bytes, 0, bytes.length);
                bufferedOutputStream.write(bytes);
                byteBuffer.clear();
            } catch (IOException e) {
                Log.e(TAG, "byteBuffer bufferedOutputStream writhing err:" + e.getMessage());
                e.printStackTrace();
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

尝试改变这个: -

try {
            byte[] bytes = new byte[1024];
            byteBuffer.get(bytes, 0, bytes.length);

            bufferedOutputStream.write(bytes);

        } catch (IOException e) {
            Log.e(TAG, "byteBuffer bufferedOutputStream writhing err:" + e.getMessage());
            e.printStackTrace();
        }

最后在操作或关闭所有内容后关闭byteBuffer。