androidnanohttpd

How to serve a mp3 file using latest NanoHTTPD 2.3.0 in Android?


I have read How to serve a file on sdcard using NanoHTTPD (inside Android)

The code return new NanoHTTPD.Response(Status.OK, "audio/mpeg", fis) doesn't be supported in latest NanoHTTPD 2.3.0 again.

I try to replace it with return newFixedLengthResponse(fis) , but it's incorrect. How can I do that? Thanks!

public class StackOverflowMp3Server extends NanoHTTPD {

    public StackOverflowMp3Server() {
         super(8089);
    }

    @Override
    public Response serve(String uri, Method method,
        Map<String, String> header, Map<String, String> parameters,
        Map<String, String> files) {
    String answer = "";

    FileInputStream fis = null;
    try {
        fis = new FileInputStream(Environment.getExternalStorageDirectory()
                + "/music/musicfile.mp3");
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return new NanoHTTPD.Response(Status.OK, "audio/mpeg", fis);
  }
}

Solution

  • You can use newChunkedResponse() method for InputStream like this:

    return newChunkedResponse(Status.OK, "audio/mpeg", fis);