我有一个应用程序使用html5让用户收听服务器上的一些音频样本。如果我在服务器上指定实际音频文件的路径,则事情按预期工作:
<audio src="/audio/english/banana_1.mp3" controls>
Your browser does not support the <code>audio</code> element.
</audio>
但是,如果我指向一个实际上是生成音频文件的servlet的资源,那么音频似乎不会播放:
<audio src="/app/dbAudio" controls>
Your browser does not support the <code>audio</code> element.
</audio>
我已经确认这个servlet会写出所需的音频文件;我已经下载并直接播放了。我还将响应contentType设置为audio / mpeg和audio / x-mpeg但没有骰子。我需要设置一些其他标题才能使其正常工作吗?谢谢你的帮助。
@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();
}