Solved

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

Posted on 2004-08-08
7
1,891 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 

Author Comment

by:david_m_jacobson
Comment Utility
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
Comment Utility

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
Comment Utility

I'm sorry, I forget this line.

sos=response.getOutputStream();
0
 

Author Comment

by:david_m_jacobson
Comment Utility
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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

This article will show you how to create an ISO CD-ROM/DVD-ROM image (*.iso), and MD5 checksum signature, for use with VMware vSphere Hypervisor 6.5 (ESXi 6.5). It's a good idea to compare checksums, because many installations fail because of a corr…
Never store passwords in plain text or just their hash: it seems a no-brainier, but there are still plenty of people doing that. I present the why and how on this subject, offering my own real life solution that you can implement right away, bringin…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

772 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

10 Experts available now in Live!

Get 1:1 Help Now