1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2002
    Rep Power

    Exclamation Creating and sending/streaming audio from a servlet

    Hi, Im a newbie here and Ive been trying to send audio from a servlet. Unfortunately, I have not been successful (not even close I think). In simple terms, what Ive tried is the following:

    1. Set the content type to audio/x-wav
    2. create a file object that opens my *.wav file
    3. create an audioinputstream and use the wav file
    4. create a bufferedoutputstream = response.getOutputStream()
    5. read from the audioniputstream and write to the bufferedoutputstream

    do these steps sound reasonable?
    Id appreciate any help!

    this is my code... (its a little messy... sorry)

    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import javax.sound.sampled.*;

    public class ServeAudio extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse resp)
    throws ServletException, java.io.IOException {

    int framesReadTotal = 0;
    File waveFile = new File( "abc.wav" );

    resp.setHeader("Content-Disposition", "filename=abc.wav") ;
    BufferedOutputStream myOutStream = new BufferedOutputStream(resp.getOutputStream() );


    AudioInputStream audioStream = AudioSystem.getAudioInputStream(waveFile);
    int bytesPerFrame = audioStream.getFormat().getFrameSize();

    int numBytes = 1024 * bytesPerFrame;
    byte[] audioBytes = new byte[numBytes];
    int numBytesRead = 0;
    int numFramesRead = 0;

    while ((numBytesRead = audioInputStream.read(audioBytes)) != -1) {

    numFramesRead = numBytesRead / bytesPerFrame;
    framesReadTotal += numFramesRead;
    catch (Exception ex){


    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    processRequest(request, response);

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    processRequest(request, response);

  2. #2
  3. No Profile Picture
    Clueless llama
    Devshed Regular (2000 - 2499 posts)

    Join Date
    Feb 2001
    Lincoln, NE. USA
    Rep Power
    I have not done what you are asking, but I believe you may be overthinking what you need to do. You are specifying that you are sending out a wav file, yet you are opening an Audiostream to get it. From reading breifly about the AudioStream, it seems to be for if you plan on using the data in an actual audio situation.

    It seems more likely to me that you should supply the file as is to the browser, who wil lthen open it in it's own audiostream since you are telling it it is an audio file. Make sense? In other words, try mearly opening the file as a File and send it out in raw bytes and see what that does.

IMN logo majestic logo threadwatch logo seochat tools logo