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.*;
7 public class Music extends HttpServlet {
9 public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
10 // 设置响应内容类型
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 }
22 }
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 }