JavaWeb向瀏覽器返回一個音頻流
阿新 • • 發佈:2017-12-31
servlet close class pos ali tps () tom servle
瀏覽器直接播放音頻文件,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 extendsHttpServlet { 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) throwsException{ 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 }
JavaWeb向瀏覽器返回一個音頻流