Using Play Framework (version 2.3.x
) (Java style), I am trying to serve an .mp3
file to the browser. Since it is a 'large' file I have decided to go with Play's ByteChunks
Object, as follows.
@With(MP3Headers.class)
public static Result test() {
Chunks<byte[]> chunks = new ByteChunks() {
public void onReady(Chunks.Out<byte[]> out) {
try {
byte[] song = Files.readAllBytes(Paths.get("public/mp3/song.mp3"));
out.write(song);
} catch(Exception e) {
e.printStackTrace();
} finally {
out.close();
}
}
};
return ok(chunks);
}
For clarification, my Mp3Headers
file, which is responsable for setting the headers so that the browser knows what type the payload has:
public class MP3Headers extends Action.Simple {
public Promise<Result> call(Http.Context ctx) throws Throwable {
ctx.response().setContentType("audio/mpeg");
return delegate.call(ctx);
}
}
For completion, my routes
file:
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
# Home page
GET / controllers.Application.index()
GET /test controllers.Application.test()
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.at(path="/public", file)
As is to be expected, navigating to localhost:9000/test
renders to a nice HTML5
audio player (see picture).
The problem I have is that 'scrolling' in the audio player does not work. If I do scroll, the music pauses, and when I let go (when I 'chose' a position in time), it continues where it first paused.
I hope that I make sense, and I hope that you guys know something more about this. Thanks in advance.
You will need to tell your browser that your server support range requests and implement the ranges responses (ie just provide the part of the music the browser needs). You can get an overview of the request/response cycle in this answer.
Note that in this code the song was already loaded in
song
. Also the parsing of theRANGE
header is very dirty (you can get values likeRANGE:
)I Found this code very easy implementation.
Put the below action and its private helper method in your controller.
Complete example link is here Byte range requests in Play 2 Java Controllers