views:

45

answers:

1

I have an application that uses html5 to let the user listen to some audio samples on the server. If I specify the path to an actual audio file on the server, things work as expected:

<audio src="/audio/english/banana_1.mp3" controls>
    Your browser does not support the <code>audio</code> element.
</audio>

However, if I point to a resource that is actually a servlet that generates the audio file, the audio doesn't seem to play:

<audio src="/app/dbAudio" controls>
    Your browser does not support the <code>audio</code> element.
</audio>

I've confirmed that this servlet does write out the required audio file; I have downloaded and played it back directly. I have also set the response contentType to audio/mpeg and audio/x-mpeg but no dice. Is there some other header that I need to set in order for this to work? Thanks for any help.

  @RequestMapping(value = "/dbAudio", method = RequestMethod.GET)
  public void getAudioFromDB(HttpServletRequest request,
        HttpServletResponse response) throws Exception{

      response.setContentType("audio/mpeg");
      // Uncommenting the next allows me to download the resource directly and 
      // confirm that it is a well formed audio file
      // response.setHeader("Content-disposition", "attachment; filename=banana.mp3");

      OutputStream o = response.getOutputStream();

      Resource r = ctx.getResources("/audio/english/banana_1.mp3")[0];
      InputStream s = r.getInputStream();

      int chunk = 0;
      while(true){
          chunk = s.read();
          if(chunk == -1) break;
          o.write(chunk);
      }
      o.flush();         
  }
+1  A: 

Try this snippet.

JRL
Uh, can you also tell why this would work instead?
BalusC
I'm no expert, but maybe due to the content length? http://www.w3.org/Protocols/HTTP/Object_Headers.html#content-length
JRL
Awesome, this link pointed out also setting the length of the response. That fixe my problem. Thanks.
darren
Ah drat, I knew that. Some apps/plugins are indeed picky when it comes to the content length :) Glad it fixed your problem.
BalusC