JavaWeb向浏览器返回一个音频流

浏览器直接播放音频文件,1是直接访问一个html的音频文件,,2 是返回一个Java音频流给浏览器解析.

下面实现一个java的wav文件音频流,可以直接播放音频文件

 1 package org.lib.speech.test;
 2 import javax.servlet.http.HttpServlet;
 3 import javax.servlet.http.HttpServletRequest;
 4 import javax.servlet.http.HttpServletResponse;
 5 import java.io.*;
 6 
 7 public class Music extends HttpServlet {
 8 
 9     public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
10         // 设置响应内容类型
11 
12          response.setHeader("Content-type", "text/html; charset=UTF-8");
13          request.setCharacterEncoding("UTF-8");//解决乱码
14          response.setContentType("text/html;charset=UTF-8");//解决乱码
15          String sentences=request.getParameter("text");
16         try {
17             sayPlay(sentences,request,response);
18         }catch (Exception e){
19             System.out.printf(e.getMessage());
20         }
21 
22     }
23 
24     public static void sayPlay (String sentences,HttpServletRequest request,HttpServletResponse response) throws Exception{
25         //获取tomcat 路径
26         String ROOT = System.getProperty("catalina.home")+"\\webapps\\JavaWeb\\test.wav";
27         //输出 wav IO流
28         try{
29             response.setHeader("Content-Type", "audio/mpeg");
30             File file = new File(ROOT);
31             int len_l = (int) file.length();
32             byte[] buf = new byte[2048];
33             FileInputStream fis = new FileInputStream(file);
34             OutputStream out = response.getOutputStream();
35             len_l = fis.read(buf);
36             while (len_l != -1) {
37                 out.write(buf, 0, len_l);
38                 len_l = fis.read(buf);
39             }
40             out.flush();
41             out.close();
42             fis.close();
43         }catch (Exception e){
44             System.out.println(e);
45         }
46      
47 
48     }

 

posted @ 2017-12-30 23:03  freedom/cn  阅读(7935)  评论(0编辑  收藏  举报