Java servlet to send audio file

Hi, I have used the example in this link http://www.java2s.com/Code/Java/Servlets/Sendmp3.htm to send a wav file to the client. I have changed the content type to audio/x-wav as I am sending a wav file not mp3 as in the example.
For some reason, it seems to send something back, but the audio file does not have any data in it (0 bytes). Eg try this link to see what happens: http://mel.our-lan.com/?=barcode50214561353872
The file browser opens up winamp/media player, but the file has no data in it. Can anybody see the problem in my code?:
String fileName = "";
                    while (rs.next())
                         fileName = rs.getString("SoundClip");
                    if (fileName == null || fileName.equals(""))
                         throw new ServletException(
                           "Invalid or non-existent file parameter in barcodeServlet.");
                    String wavDir = ("http://mel.our-lan.com/wav-dir/" + fileName);
                         /*getServletContext().getInitParameter("wav-dir");*/
                    if (wavDir == null || wavDir.equals(""))
                      throw new ServletException(
                           "Invalid or non-existent wavDir context-param.");
                    ServletOutputStream stream = null;
                    BufferedInputStream buf = null;
                    try
                         stream = response.getOutputStream();
                         File wav = new File(wavDir + "/" + fileName);
                         //set response headers
                         response.setContentType("audio/x-wav");
                         response.addHeader("Content-Disposition", "attachment; filename="
                              + fileName);
                         response.setContentLength((int)wav.length());
                         FileInputStream input = new FileInputStream(wav);
                         byte[] buf1 = new byte[1024];
                         int len;
                         while ((len = input.read(buf1)) > 0)
                              stream.write(buf1, 0, len);
                         /* TRIED THE FOLLOWING ASWELL BUT SAME RESULT:
                                        buf = new BufferedInputStream(input);
                         int readBytes = 0;
                         //read from the file; write to the ServletOutputStream
                         while ((readBytes = buf.read()) != -1)
                              stream.write(readBytes);*/
                         input.close();
                    catch (IOException ioe)
                         throw new ServletException(ioe.getMessage());
                    finally
                         if (stream != null)
                              stream.close();
                         if (buf != null)
                              buf.close();
                    }

I tried the link; got the following:
java.lang.NullPointerException
     BarcodeServlet.doPost(BarcodeServlet.java:23)
     BarcodeServlet.doGet(BarcodeServlet.java:17)
     javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
     javax.servlet.http.HttpServlet.service(HttpServlet.java:803)Take a look at this example, [1],might help you some.
[1] http://balusc.blogspot.com/2007/07/fileservlet.html
People on the forum help others voluntarily, it's not their job.
Help them help you.
Learn how to ask questions first: http://faq.javaranch.com/java/HowToAskQuestionsOnJavaRanch
(Yes I know it's on JavaRanch but I think it applies everywhere)
----------------------------------------------------------------

Similar Messages

  • How to send audio files as attachments?There is no attachment option in mail and no share option in MUSIC

    How to send audio files as attachments?There is no attachment option in mail and no share option in MUSIC

    i have some voice samples in Music file .how to share those files? or plz tel me where to store the voice samples

  • Premiere Pro CC not sending Audio files to edit on Audition CC

    Hey guys so i just Upgraded from CS6 to CC. Before i did PremiereCS6 was sending audio files to AuditionCS6 with no problems. Since yesterday that i upgraded the option is greyed out and i cant do it. Not sure if this is something happening to a lot of people or just me. Any help would be appreciated. Thanks!

    Well if anyone stumbles here for the same reasons i posted i finally found a fix that doesnt involve re-install from another thread. here is the answer it works like a charm.
    I had this problem and fixed it pretty quick without the need to uninstall and reinstall.
    Look for the default .sesx files in your Document/Adobe/Audition/6.0/Session Templates folder (on Windows 7)
    There should be a list of preset .sesx files. Right-click one and set its default application as Adobe Audition by using the "open with" option.
    Once I did this I double-clicked to open the .sesx files with Audition, closed it, opened Premiere Pro CC and VUAAA-LAAA the button is available and fully functional.
    Hope this helps someone!

  • Sending audio files through web service

    Hi,
    How can we send audio (mp3,wmv) files through web services ? i have tried making a byte array of the file and then sending the byte array through the web service, but it give OutOfMemory error. so is there any better and practical way of doing it ?

    Just read catalina.bat and find where $JAVA command is called, for NT it should be "%_EXECJAVA% %JAVA_OPTS% %CATALINA_OPTS% "
    "%_EXECJAVA% is java
    %JAVA_OPTS% and %CATALINA_OPTS% are enviroment parameter for java command. Just added one of them in your case.
    By the way, " i am using a HP PDA on the client side, so i cannot increase the JVM heap size there", you should info. the client, otherwise the client may be get "out of memory".

  • Problem Premiere CC not sending audio file to Adobe Audition

    Hello,
    I have an audio clip in Premiere Pro CC that I am attempting to send to Audition via dynamic link with "Edit Clip In Adobe Audition."  I have done this in the past but not since I have upgrade all my versions from the CS6 version to the CC 2014 versions.  Previously it worked without incident.  Here is what happens now.
    1.  I right click the audio track (Mono-005.wav) in the premiere pro cc timeline.
    2.  I select "Edict Clip in Adobe Audition.
    3.  In Premiere Pro CC a new audio track is generated (MONO-005 Audio Extracted.wav) on the timeline - replacing the previous track (MONO-005.wav) and in my Premiere Pro CC media bin BUT it never opens up in Adobe Audition....the program (Adobe Audition) never even attempts to open up.
    I was getting the Audition error "primary temp volume cannot be found" so I went in to Audition and changed the Media & Disk Cache file location and now I can open up the Adobe Audition program just fine if I am clicking it directly to open.  However, whenever I attempt to bring an audio file from premiere with dynamic link (as referenced above) Audition does not even attempt to open.
    Software
    Adobe Audition Build 7.2.0.52
    Adobe Premiere Pro CC Build 8.1.0 (81)
    Computer
    Processor - Intel (R) Xeon (R) CPU   X5560 @ 2.80 GHz 2.79 GHz (2 processors)
    RAM 48 GB (currently 40 GB usable)
    64 bit operating system
    Windows 7 Professional Service Pack 1
    Thanks in advance for any assistance.

    Had this issue before.  Check the file associations to see if Audition CC 2014 is set as the default editing program to open sesx files, etc.
    You might want to make sure that all the other apps are set as well.  I have three versions of the software on my machine, and I had to do this to ensure the latest version was set as the default app for the appropriate file types to make dynamic linking work.

  • Sending Audio Files back to Final Cut pro, nothing.

    Simple issue:
    I send from Final Cut Pro To Sound track pro some audio files along with the clip.
    I edit it in Sound track Pro, and save (just like in the tutorial) then I quit.
    I go back to Final Cut Pro and what do you know, the file that I sent HAS NOT BEEN EDITED!
    Some one help.

    I tried the same thing earlier in the year, and when the sound came back into FCP, it was corrupted!
    Since then, I don't know if this is a good option, but it seems to work fine:
    Once I have finished my editing in FCP, I export the soundtrack into an AIFF. I edit the AIFF via STP, and when finished, import it back into FCP.
    I'm not experienced enough to know if this method is bad, but it has worked well for me!

  • How to send audio files in iMessage

    Anyone know how to send an audio file as either an SMS/MMS using iPhone 4S/iMessage? Thanks!

    i have some voice samples in Music file .how to share those files? or plz tel me where to store the voice samples

  • Sending audio file with lumia 630

    Audio file and videos which we download ,can't be sent via whatsup to other contacts on Lumia 630. What is solution?

    Audio files sent supported yet, for video, move the video file to a folder inside the Pictures folder and then select it for sending inside WhatsApp.

  • What is wrong with the following Java servlet code that downloads files?

    Hi,
    I need urgent help.
    This is the issue. I have a JSP code that calls a Java servlet class. This class is used to download files from the JSP page. The following is the piece of code that does the file download.
    String pathOfFile = gsPath + "/" + gsFileName.substring(gsFileName.indexOf("~")+1);
    File F = new File(pathOfFile);
    res.setContentType("application/stream");
    res.setHeader("Content-Disposition", "attachment; filename=" +gsFileName.trim());
    This code works just fine with IE. However, when this is used with Netscape, the class name gets added to the original file name extension. For example, if the class name is 'FileRetriever' and the file being downloaded is originally named 'a.doc', the file gets a name of 'a.doc.FileRetriever' after download using Netscape or Mozilla.
    One way to solve this is by adding the appropriate file type in the MIME settings in browser preference. However, this not a permanent solution.
    Can somebody let me know the correct code to fix this issue?
    Thanks for your time.

    We loose control of the file name once we pass the original file name to the input stream. When our code instructs Netscape to write the file on the local disk using an output stream, that is when Netscape/Mozilla adds this additional extension to the original file. So, essentially, we do not know about this additional extension.
    Any ideas on how to resolve this?
    Thanks.

  • Sending audio file using Mac Mail

    What would be the best way to send a short audio clip using Mac Mail to recipients who all have PC's?

    All I know is sometimes I receive documents, audio or video clips from friends who have PC's and they can't be played or opened up on my Mac because I don't have the proper applications to open them.
    I would assume the reverse could also happen depending on the program that created them.
    As an example: What if I send an audio clip taken from my iTunes Library and the person who receives it doesn't have iTunes and the only other program they have is Windows Media Player. Will they be able to open this file up?
    Thanks.

  • Can you send audio files by mms?

    thank you in advance.

    Sharing Voice Memos
    You can share your voice memos as attachments in email or MMS messages
    (iPhone 3G or later).
    Share a voice memo:
    1 On the Voice Memos screen or Info screen, tap Share.
    2 Choose Email Voice Memo to open a new message in Mail with the memo attached,
    or choose MMS to open a new message in Messages.
    A message appears if the file you’re trying to send is too large.
    http://manuals.info.apple.com/enUS/iPod_touch_3.0_UserGuide.pdf , page 127
    Message was edited by: Ingo2711

  • Premiere Crashes when sending Audio File to Audition

    On OSX Lion, 12-core Mac Pro...
    Premiere crashes whenever I attempt to EDIT a file to Audition from timeline.  Happenes everytime.  Fully updated on all programs...

    Best to post specific product questions in that product's forum
    http://forums.adobe.com/community/premiere/premierepro_current?view=discussions

  • How to send a file from a java program to a servlet and get a response

    Hi,
    How can I call a servlet from a standalone java program and send a file to a servlet using POST method and in return gets the status back from the servlet. Any help is appreciated any small sample will help.
    Thanks.

    Hi,
    I am trying the following sample I got from net and am getting the following error. Any help what I am doing wrongs:
    06/12/24 02:15:58 org.apache.commons.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is null
    06/12/24 02:15:58      at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:294)
    06/12/24 02:15:58      at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:268)
    06/12/24 02:15:58      at mypackage9.Servlet1.doPost(Servlet1.java:38)
    06/12/24 02:15:58      at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
    06/12/24 02:15:58      at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    06/12/24 02:15:58      at com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:65)
    06/12/24 02:15:58      at oracle.security.jazn.oc4j.JAZNFilter.doFilter(Unknown Source)
    06/12/24 02:15:58      at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:663)
    06/12/24 02:15:58      at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:330)
    06/12/24 02:15:58      at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:830)
    06/12/24 02:15:58      at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:285)
    06/12/24 02:15:58      at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:126)
    06/12/24 02:15:58      at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:192)
    06/12/24 02:15:58      at java.lang.Thread.run(Thread.java:534)Here is the sample client code:
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.methods.PostMethod;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    public class PostAFile {
        private static String url =
             "http://192.168.0.17:8988/Vulcan_Materials-ServletPost2-context-root/servlet/Servlet1";
        public static void main(String[] args) throws IOException {
            HttpClient client = new HttpClient();
            PostMethod postMethod = new PostMethod(url);
            client.setConnectionTimeout(8000);
            File f = new File("C:\\load.txt");
            System.out.println("File Length = " + f.length());
            postMethod.setRequestBody(new FileInputStream(f));
            int statusCode1 = client.executeMethod(postMethod);
            System.out.println("statusLine>>>" + postMethod.getStatusLine());
            postMethod.releaseConnection();
    }Here is the sample servlet code:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.PrintWriter;
    import java.io.IOException;
    import org.apache.commons.fileupload.DiskFileUpload;
    import org.apache.commons.fileupload.FileItem;
    import java.util.List;
    import java.util.Iterator;
    import java.io.File;
    public class Servlet1 extends HttpServlet
      private static final String CONTENT_TYPE = "text/html; charset=windows-1252";
      public void init(ServletConfig config) throws ServletException
        super.init(config);
      public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
        try
          response.setContentType(CONTENT_TYPE);
          PrintWriter out = response.getWriter();
          java.util.Enumeration e= request.getHeaderNames();
            while (e.hasMoreElements()) {
              String headerName=(String)e.nextElement();
              System.out.println(headerName +" = "+request.getHeader(headerName));
           //System.out.println("Content Type ="+request.getContentType());
            DiskFileUpload fu = new DiskFileUpload();
            // If file size exceeds, a FileUploadException will be thrown
            fu.setSizeMax(1000000);
            List fileItems = fu.parseRequest(request);
            Iterator itr = fileItems.iterator();
    System.out.println("***************************");
            while(itr.hasNext()) {
              FileItem fi = (FileItem)itr.next();
              //Check if not form field so as to only handle the file inputs
              //else condition handles the submit button input
              if(!fi.isFormField())
                System.out.println("\nNAME: "+fi.getName());
                System.out.println("SIZE: "+fi.getSize());
                //System.out.println(fi.getOutputStream().toString());
                File fNew= new File("C:\\", fi.getName());
                System.out.println(fNew.getAbsolutePath());
                fi.write(fNew);
              else
                System.out.println("Field ="+fi.getFieldName());
            out.println("SUCCESS123456: ");
          out.close();
        catch(Exception e)
          e.printStackTrace();
    }Any help on what is wrong.
    Thanks

  • Error while running Java program which call a file upload servlet

    Hi all,
    I have a java program which calls a servlet and sends the file to be uploaded by the servlet. I used Jbuilder to create java program and servlet program. I compiled both the programs and compilation suceeded and my class files are avaialbe in
    WEB-INF/classes/content directory. But now I am trying to run the Java program(this contains main method) from the command prompt, which should inturn call my servlet.(I have web.xml file inside WEB-INF dir). But I receive the following error
    C:\tomcat5.5.15\apache-tomcat-5.5.16\webapps\content\WEB-INF\classes\content>java MultiContentSender
    Exception in thread "main" java.lang.NoClassDefFoundError: MultiContentSender (w
    rong name: content/MultiContentSender)
    at java.lang.ClassLoader.defineClass0(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:537)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:12
    3)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:251)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:55)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:194)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:187)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:289)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302)
    My dir strcture is as below
    TOMCAT_HOME/webapps/content/WEB-INF/classes/content/*.class
    I am not able to figure out the error, can anyone throw some light on this issue.

    You are trying to invoke the class from the command prompt. My guess is that MultiContentSender contains a package, which means that you'll need to add your WEB-INF\classes directory to the classpath before it will work. Classes stored in this directory are expected to be invoked through tomcat, which builds it's own classpath.

  • Sending audio data over http problem

    Hi Guys,
    We are trying to create a little servlet in Tomcat, which is capable to send audio files over http to an embedded media player. The definition of the player looks like:
    <OBJECT ID="Mp" CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" TYPE="application/x-oleobject" WIDTH="0" HEIGHT="0">
    <PARAM name="uiMode" value="none">
    <PARAM NAME="ShowControls" VALUE="0">
    <PARAM NAME="AutoStart" VALUE="1">
    <PARAM NAME="ShowPositionControls" VALUE="0">
    <PARAM NAME="ShowStatusBar" VALUE="0">
    <PARAM NAME="ShowDisplay" VALUE="0">
    </OBJECT>
    <script language="javascript">document.Mp.URL = "here comes the url of the servlet with item ID";</script>
    The servlet reads the audio file and writes its content to the response with the following http header settings:
    getResponse().setContentType("audio/x-wav");
    getResponse().setHeader("Content-Transfer-Encoding", "binary");
    getResponse().setHeader("Pragma", "Public");
    getResponse().setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    getResponse().setHeader("Content-Disposition", "inline; filename=Media.wav");
    getResponse().setHeader("Content-Length", new Integer(MediaBytes.length).toString());
    getResponse().setHeader("Accept-Ranges", "bytes");
    So, everything works fine for wav files in Internet Explorer, but we are facing problems with Firefox, where it does not work. The embedded Media Player says that "Windows Media Player cannot play the file. One or more codecs required to play the file could not be found."
    But if we set the url to directly to the file on the server, everything works fine.
    We have analyzed the HTTP traffic in both situation, but we cannot understand how Internet Explorer/Firefox and Media Player works together:
    - how does Media Player know that the audio file is playable?
    - if the url points directly to the file, the HTTP headers does not contain any kind of information about the file type, only the extension is available; Media Player checks the file extenion in the url?
    - if the url points to the servlet, why Media Player in Firefox cannot determine the file type and throws error?
    Any help is greately appreciated!
    Thanks!
    Gabor

    If you haven't already, I would try breaking down the problem. First confirm you're getting serial data then confirm that netcat can send some data. Like this:
    xxd < /dev/tty.usbmodemfa121 | less
    nc -u 10.0.1.3 7000 <<< 'hello over there'

Maybe you are looking for