Solved

How to play a wav file that resides on an application server using JSP and Java

Posted on 2004-08-08
7
1,925 Views
Last Modified: 2011-09-20
I am trying to play a wav file from a JSP page.  The wav file is on a tomcat server and the Apache web server is on a separate server.  That is, the wav file does not exist on the web server.  The wav file only exists on the tomcat server.

I have tried two methods.  The first method is to use a servlet that parses through the wav file and returns the wav file.

The second method is to use an AudioClip object to play the wav file.

Both methods have worked on my local development PC that has both tomcat and Apache on the same PC.  But when I upload either version to the test server it does not work.

With the first method, I get an error that it can't find the URL that I mapped the servlet to.  I'm not sure why because I did modify web.xml to map the servlet to the URL.

Likewise, the second method didn't work either.  This time there was no error message, I just couldn't hear the sound.  Is this because the sound was playing on the test server and not on my PC (about 1,000 miles away from the test server)?  I thought that it is possibly not pointing to the wav file on the server but I verified that the wav file is on the server and it looks like the code is pointing to the right directory.

Here is the code that is in my JSP for METHOD 1:

response.sendRedirect("/Listen2.html?file=sFileName);

and then the code for the servlet, DownloadServlet, which is mapped to Listen2.html is:

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet implements Servlet {

      public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
                  
            doPost(req, resp);
      }

      public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
            
            //This servlet simply sends out the specified file with a mime type set.
            // File path supplied should be specified from the context root.
            String file = req.getParameter("file");
            if (file != null && file.trim().length() != 0) {
                  URL url = getServletContext().getResource(file);
                  if (url != null) {
                        URLConnection con = url.openConnection();
                        resp.setContentType(con.getContentType());
                        //System.out.println(con.getContentType());
                        resp.setContentLength(con.getContentLength());
                        //System.out.println(con.getContentLength());
                        resp.setHeader("Content-Disposition", "attachment; filename=" + getFileName(url));
                        //System.out.println(getFileName(url));
                        
                        ServletOutputStream out = resp.getOutputStream();
                        BufferedInputStream in = new BufferedInputStream(con.getInputStream());
                        byte[] buf = new byte[5120];

                        int len;
                        while ((len = in.read(buf)) > 0) {
                              out.write(buf);
                        }
                        int i;
                        in.close();
                        out.flush();
                        out.close();
                  }
            }
      }
      
      private String getFileName(URL url) {
            String path = url.getFile();
            return path.substring(path.lastIndexOf('/')+1);
      }
}

Here is the code that is in my JSP for METHOD 2:

URL base = new URL("file:" + request.getSession().getServletContext().getRealPath("/"));
AudioClip clip = Applet.newAudioClip(new URL(base, sFileName));
clip.play();

sFileName is just the name of the wav file that should be played.

I like version two because it is a lot less code and it does not require a redirect to a separate page.

I am running on Windows XP while the test server is a Unix box. There is a possibility that I am not running the same versions of everything (e.g., JDK). Would this make a difference?

Any help would be much appreciated.

Dave
0
Comment
Question by:david_m_jacobson
  • 3
  • 2
  • 2
7 Comments
 
LVL 1

Assisted Solution

by:TomBruser
TomBruser earned 200 total points
ID: 11748007
Code that is in your JSPs (and other servlets) runs on the application server.  To make things happen on the client side (machine running the web browser) you need to write it for the client side.  If you got the servlet you've written to run, yes, if the server running the servlet had access to an audio device, the sound would be playing on the server, not your local workstation. If you want your browser to play sound that is provoked by your having accessed a JSP page, then output some HTML that is intended for downloading and playing the WAV file.  Note that the WAV file has to be accessible to the browser.  You can test this by entering in the URL that you expect to be able to access the WAV file from.  Likely your web browser will play the sound anyway w/o any programming depending on what you have set up.  If you want anything fancier than that, Flash makes for a good transport for streaming an MP3 based audio clip in a person's browser.
0
 

Author Comment

by:david_m_jacobson
ID: 11749430
If I understand this comment correctly, I need to have the wav file accessible to the web server.  The problem with this is that I am creating the wav file dynamically using a Java class on the application server.  So if the Java class is on the application server, how is it possible to either put the file on the web server or make the file accessible to the web server?

Dave
0
 
LVL 1

Assisted Solution

by:TomBruser
TomBruser earned 200 total points
ID: 11752105
You can always use a servlet to transmit the contents of the wav file, proper mime type, etc.  If the wav file is located on a hard drive, use a FileInputStream, fetch the WAV with it, and output the bytes to your servlet.  You might have to play around with the mime headers (response.setHeader()) but that's really all there is to it.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:david_m_jacobson
ID: 11752114
Do you mean like the code above?  Is there anything wrong with the servlet code?
0
 
LVL 1

Accepted Solution

by:
phupha earned 300 total points
ID: 11755498

Method 1: you retrieve sound data via http protocol
Try to get them directly from files system.


This is an example

ServletContext application=getServletContext();
String responseCt="audio/x-wav";
response.setContentType(responseCt);
response.addHeader("Content-Disposition","attatchment; filename=\"download.wav\"");

ServletOutputStream sos=null;
File file="{Path to your wavfile}/{wav file name}";
FileInputStream fis=new FileInputStream(file);
BufferedInputStream bis=new BufferedInputStream(fis);
byte fdata[]=new byte[256];
int numRead=0;
while((numRead=bis.read(fdata))!=-1) sos.write(fdata,0,numRead);


Finally : don't forget to close file after use
fis.close();bis.close();

0
 
LVL 1

Assisted Solution

by:phupha
phupha earned 300 total points
ID: 11755556

I'm sorry, I forget this line.

sos=response.getOutputStream();
0
 

Author Comment

by:david_m_jacobson
ID: 11758943
Thanks for the help.  This is pretty much solved.  I didn't understand all the configuration required with Apache and Tomcat:

- add a line in the Apache httpd referenced config file to "JkMount /.../servlet/* xxx"

Other than that, method 1 works.  Thanks for the help.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
JTable - RowFilter & Columns Header. 3 140
maven project in eclipse 11 57
EJB MDB example 4 79
timeToIdleSeconds vs timeToLiveSeconds in hibernate second level cache 3 97
This article lists the top 5 free OST to PST Converter Tools. These tools save a lot of time for users when they want to convert OST to PST after their exchange server is no longer available or some other critical issue with exchange server or impor…
When we talk about DevOps toolchains, I sometimes wonder how many people really get what we’re talking about. I don’t know if it’s just semantics or tone or something else, but sometimes I think it just sounds like buzzword sausage. So it’s always …
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
Need to grow your business through quality cloud solutions? With everything required to build a cloud platform and solution, you may feel like the distance between you and the cloud is quite long. Help is here. Spend some time learning about the Con…

929 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now