我想在MediaPlayer中播放数据时缓存数据 . 在我阅读时,有一种方法可以做到这一点 - 创建自己的本地http服务器并将本地URL设置为MediaPlayer的setDataSource(字符串路径) .

我使用NanoHTTPD作为本地服务器 . 有服务代码功能:

@Override
    public Response serve(String uri, Method method, Map headers, Map parms, Map files)
    {
        try
        {
            // delete / character
            URL url = new URL(uri.substring(1));
            URLConnection connection = url.openConnection();
            connection.connect();

            File cacheFolder = new File(Environment.getExternalStorageDirectory(), "TracksFlowCacheNew");
            Log.e("RelayServer", "Cache to file " + Utils.md5(url.toExternalForm()));
            RelayInputStream ris = new RelayInputStream(connection.getInputStream(), new FileOutputStream(new File(cacheFolder, Utils.md5(url.toExternalForm()))));


            return new Response(Response.Status.OK, NanoHTTPD.MIME_DEFAULT_BINARY, ris);
        }
        catch(MalformedURLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch(FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch(IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

RelayInputStream扩展InputStream . 我试图在那里缓存数据:

private class RelayInputStream extends InputStream
    {
        private InputStream mInputStream = null;
        private OutputStream mOutputStream = null;

        public RelayInputStream(InputStream is, OutputStream os)
        {
            mInputStream = is;
            mOutputStream = os;
        }

        @Override
        public int available() throws IOException
        {
            Log.e("available", "available = " + mInputStream.available());
            mInputStream.mark(mInputStream.available());
            return mInputStream.available();
        }

        @Override
        public int read(byte[] buffer) throws IOException
        {
            Log.e("read", "buffer = " + buffer.toString());
            mOutputStream.write(buffer);
            return mInputStream.read(buffer);
        }

        @Override
        public int read(byte[] buffer, int offset, int length) throws IOException
        {
            Log.e("read", "buffer = " + buffer.toString() + "; offset = " + offset + "; length = " + length);
            mOutputStream.write(buffer, offset, length);
            return mInputStream.read(buffer, offset, length);
        }

        @Override
        public int read() throws IOException
        {
            Log.e("read", "no data");
            byte[] b = new byte[1];
            mInputStream.read(b);
            mOutputStream.write(b);
            mInputStream.close();
            mOutputStream.close();
            return b[0] & 0xff;
        }
    }

但是RelayInputStream可用只返回很少的下载字节 . 因此,只有很少一部分数据被缓存并返回给媒体播放器 . 那么,我做错了什么?如何转发和缓存所有流?