Help on playing sound

Hi there,
I want to play a sound file without the dependence
on any web browser. Below is my simple Java code.
When I test it on DOS prompt, it can play the desired
sound file. However, the system keep hanging after
the play of the sound. Can anyone tell me what's
the problem of my code? Alternatively, is there any
better Java code (not applet) to play a sound file?
import java.io.*;
import java.net.*;
import java.applet.*;
public class testAudio{
     public static void main(String args[]){
          try{
               URL baseURL = new URL("file:" + System.getProperty("user.dir") + "/");
               String relativeURL = "spacemusic.au"; // any audio file you want to play
               URL completeURL = new URL(baseURL, relativeURL);
               System.out.println(completeURL);
               AudioClip sound = Applet.newAudioClip(completeURL);
               if (sound == null) {
          System.out.println("Sound " + relativeURL + " not loaded yet.");
               sound.play();
          catch (MalformedURLException e){
               System.err.println(e.getMessage());
Thanks a bunch,
- John

Using this method to play a sound spawns a thread that plays the sound (so the app isn't blocked until the sound finishes). Doing this stops the app from terminating (much like if you created a Frame object). You can use System.exit(0); to force an application termination. I've found using AudioClip to very bug-prone. Its much better to use the javax.swing packages:
http://java.sun.com/products/java-media/sound/index.html

Similar Messages

  • Help with playing sound in applications

    im new to java and i was practicing playing sound in a swing application but the problem is that when i press the play button no sound is played...here is my code
    import javax.swing.*;
    import java.applet.AudioClip;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.io.File;
    public class JukeBox extends JFrame {
        private JLabel label;
        private JPanel panel, buttonPanel;
        private JComboBox playList;
        private JButton play, stop;
        private URL url1, url2, url3, url4, url5, url6;
        private AudioClip[] musicList;
        private AudioClip current ;
        public JukeBox() {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(500, 120);
            setLocation(50, 50);
            setTitle("JAVA JukeBox");
            url1 = url2 = url3 = url4 = url5 = url6 = null;
            current = null;
            try {
                url1 = new URL("file", "localhost", "C:\\Documents and Settings\\KADA\\IdeaProjects\\Sound\\bottle-open.wav");
                url2 = new URL("file", "localhost", "C:\\Documents and Settings\\KADA\\IdeaProjects\\Sound\\BP2.mp3");
                url3 = new URL("file", "localhost", "C:\\Documents and Settings\\KADA\\IdeaProjects\\Sound\\fhm.aiff");
                url4 = new URL("file", "localhost", "C:\\Documents and Settings\\KADA\\IdeaProjects\\Sound\\jungle.rmf");
                url5 = new URL("file", "localhost", "C:\\Documents and Settings\\KADA\\IdeaProjects\\Sound\\spacemusic.au");
                url6 = new URL("file", "localhost", "C:\\Documents and Settings\\KADA\\IdeaProjects\\Sound\\trippygaia.mid");
            } catch (MalformedURLException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            musicList = new AudioClip[7];
            musicList[0] = null;
            musicList[1] = JApplet.newAudioClip(url1);
            musicList[2] = JApplet.newAudioClip(url2);
            musicList[3] = JApplet.newAudioClip(url3);
            musicList[4] = JApplet.newAudioClip(url4);
            musicList[5] = JApplet.newAudioClip(url5);
            musicList[6] = JApplet.newAudioClip(url6);
            label = new JLabel("JAVA JukeBox", JLabel.CENTER);
            String[] musicList = {"select a track..."
                    , "bottle open"
                    , "bitch please II"
                    , "flutte, harmonica, mambo"
                    , "jungle"
                    , "spacemusic"
                    , "trippygaia"};
            playList = new JComboBox(musicList);
            playList.addActionListener(new ListListener());
            play = new JButton("Play");
            play.setActionCommand("play");
            play.addActionListener(new ButtonListener());
            stop = new JButton("Stop");
            stop.addActionListener(new ButtonListener());
            buttonPanel = new JPanel();
            buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
            buttonPanel.add(play);
            buttonPanel.add(stop);
            panel = new JPanel();
            panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
            panel.add(label);
            panel.add(Box.createRigidArea(new Dimension(0, 5)));
            panel.add(playList);
            panel.add(Box.createRigidArea(new Dimension(0, 5)));
            panel.add(buttonPanel);
            getContentPane().add(panel);
        private class ButtonListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                if(current != null){
                    current.stop();
                if(e.getActionCommand().equalsIgnoreCase("play")){
                    if(current != null){
                        current.play();
        private class ListListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                if (current != null) {
                    current.stop();
                current = musicList[playList.getSelectedIndex()];
        public static void main(String[] args) {
            setDefaultLookAndFeelDecorated(true);
            JukeBox jb = new JukeBox();
            jb.setVisible(true);
            jb.setResizable(false);
    }can u please tell me whats wrong with my code coz i cant hear no sound when i press the play button and can u please tell me why i cant simply put the file name in the URL instead of the complete path although the files are in the same directory of the source code and can i play mp3 using this little program ???
    plz help...im a newbie so plz explain as much as u can...

    After
    musicList = new AudioClip[7];
            musicList[0] = null;
            musicList[1] = JApplet.newAudioClip(url1);
            musicList[2] = JApplet.newAudioClip(url2);
            musicList[3] = JApplet.newAudioClip(url3);
            musicList[4] = JApplet.newAudioClip(url4);
            musicList[5] = JApplet.newAudioClip(url5);
            musicList[6] = JApplet.newAudioClip(url6);initialise the variable current with
    current = musicList[1];or similar because the AudioClip current always == null in your code so your listener blocks don`t execute.
    regards

  • Help on Play Sound File.vi - file format

    Hello,
    My request is quiet simple but I don't understand why it doesn't work.
    I want read a .wav sound file with the Play Sound File vi. But when I run the vi, an error message appears " Cannot recognize sound format"
    I have tried with different .wav sound files but nothing works.
    Do you know why this error happens ?
    Thanks
    Attachments:
    Sound_Labview.png ‏142 KB

    Ok thanks.
    Since the last time I posted I've tried many other wav sounds but nothing works I still had the same Labview error.
    I join you few of my wav files and maybe you can try it.
    Thanks
    Attachments:
    wav.zip ‏160 KB

  • [help]ABOUT play sound

    CFURLRef myURLRef;
    myURLRef = CFURLCreateWithFileSystemPath (kCFAllocatorDefault,
    CFSTR("/aif.aif") ,
    kCFURLPOSIXPathStyle,
    FALSE);
    OSStatus error = AudioServicesCreateSystemSoundID (myURLRef, &mySSID);
    this code can play sound in the root directory.
    but how can I play the sound in the resource Bundle?
    thanks a lot

    OK, I find it
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    // Look for a resource in the main bundle by name and type.
    myURLRef = CFBundleCopyResourceURL( mainBundle,
    CFSTR("fun"),
    CFSTR("aif"),
    NULL );
    if you have some question, MSN me: [email protected]

  • Help! My phone will not play sound when an app is open?!

    Seemingly out of the blue, my iPhone stopped playing sound through the external speaker. This began about a month or two ago and I have been unable to fix the problem. The sound will play through the external speaker until I open another app (safari, camera, etc.). The sound used to work through headphones until this morning. Now the sound won't work... At all! I brought my phone to an apple store a week ago and the first guy checked my phone with a flashlight and told me first that there didn't seem to be any water damage. Then, some other technician helped me. He opened iTunes and miraculously, the song played! I couldn't believe it was magically working. He explained that it looked like my dock connector was looking a little eroded and that is why the sound doesn't work. He said he could try to brush it out and that should fix the problem. Tried my phone later... Volume doesn't work anymore! The dock connector works fine otherwise, I am still able to charge my phone. My phone will not play music via bluetooth speaker. I talked to multiple people on the phone who all seem to think it's a software problem... I am really not understanding what is going on with my phone! I have googled this problem many times in the last few months and most people say that it turned out to be a software issue. I have checked both water indicators (in the dock connector and the headphone plug, right?) with a flashlight and I don't see any red... Any insight or ways to fix this would be very appreciated! The whole thing makes no sense to me.

    Are you using an APple charger or a thrid-party one?  I ask because if you are using a third party charger, it may not be wired properly and it may be telling your iPhone that the cable connected is also an audio interface so your iPhone may be sending the audio signals through the cable to the charger.  I have a charger in my truck that also doubles as an FM transmitter so I can play my iPhone audio through the truck radio.  Your charger may be doing something similar, especially if it is not an Apple charger.

  • Multimedia Speaker System will not play sound.. Please help me!!!

    Hello every body. (I'm not so good at english) I has a problem. My Creative Inspire 4.1 4400 will not play sound. Only at of 4, I can hear musik(or sound). Yesterday I tryed to do it good again, but not the problem is therenow. Some time, the computer will not play music or DVDs, but it can play MSN sounds, and I must re-start the computer, and so it will play music and DVD... What is the problem? What can I do? Please help me! I hobe you understand my english. If not, ask me and I can try again. Have a nice evening!

    If you can help me, please write on easy english.

  • Please.. need help!! Problem with playing sounds

    Hello, any help at all greatly appreciated.
    I need a dead-certain way of playing sounds with my java application.
    Java media player doesn't seem to be working with sound files with a duration of longer than 30 seconds.
    I need a way of accessing the windows sound API from inside my java app.
    Anyone have any ideas??????

    Hello, any help at all greatly appreciated.
    I need a dead-certain way of playing sounds with my java application.
    Java media player doesn't seem to be working with sound files with a duration of longer than 30 seconds.
    I need a way of accessing the windows sound API from inside my java app.
    Anyone have any ideas??????

  • My iPhone 4s refuses to play sound when the headphones are not in. When the headphones are in however, it works perfectly fine! This is most annoying, could someone please help me :)

    My iPhone 4s refuses to play sound when the headphones are not in. When the headphones are in however, it works perfectly fine! This is most annoying, could someone please help me   I have not dropped it and it has not been in any contact with liquid.

    I just tried both of those things and to no avail. Here are some pictures if that will help

  • Dv6 Only plays Sound out of the built in speakers if headphones are plugged in ...please help

    My Pavillon Dv6 Only plays Sound out of the built in speakers if headphones are plugged in. It plays sound from both when there plugged in. Please hep me.

    Step 1:
    In troublshooting the problem you may follow the steps provided below.
      a. Click Start, type Sound in the Start Search box. 
      b. Click Sound in the search results at the top of the Start menu. 
      c. Click the Playback tab. Notice the check mark next to the default device. For most users,the default device is speaker, change it to headphones. Make sure that your audio settings are configured as expected.
    Step 2:
    On the Playback tab, select the playback device, click Properties, click the Advanced tab, and make sure that the Default Format is set to the value that you expect. When you finish, close this window to return to the previous window.
    Step 3:
    On the Playback tab, select the playback device, click Configure, and then make sure the configurations are set correctly.
    Method 2:
    If the issue persists then I suggest you to follow these below mentioned steps to mute all other sounds when windows detects any communications activity.
      a. Click Start, type Sound in the Start Search box. 
      b. Click Sound in the search results at the top of the Start menu. 
      c. Click the Communications tab.
      d. Click on the radio button according to your convenience, under When Windows detects communications activity.
    After performing the above steps you may check for the issue.
    For more troubleshooting you may visit this below mentioned link.
    Tips for fixing common sound problems
    http://windows.microsoft.com/en-us/windows7/Tips-for-fixing-common-sound-problems 
    Let us know how it goes!
    "I work for HP."
    ****Click the (purple thumbs up icon in the lower right corner of a post) to say thanks****
    ****Please mark Accept As Solution if it solves your problem****
    Regards
    Manjunath

  • JMStudio locks up playing sound file - using java 1.5.0_02 - HELP!

    I'm using the jmf 2.1.1e cross platform version on Windows XP SP2. I have java 1.5.0_02 installed.
    When I open the sound file using JMStudio it locks up. It plays videos that don't have sound fine, so it's not the video. It's the sound that is killing it.
    Does anyone have any suggestions?

    Hi,
    yeah it's possible to play sound on Windows but you have to use the Windows Performance Pack instead of the crossplatform-version of JMF.
    This has to do with the JavaSound Architecture of Java 5.0. They made changes and now the JavaSound Renderer didn't work under Windows but the DircetSound Renderer works fine.
    So be sure that your application uses the DirectSound Renderer!
    This is one of the main problems of JMF but now Sun gets interested in JMF and they would build a new version of JMF. If this is true they have to fix this problem!
    Best regards, thomas

  • I need help i dropped my phone in water, dried it, and now it wont play sound except for on the headphones

    i dropped my phone in water and now it wont play sound except in headphones and i even dried it!

    You'll have to buy an out of warranty phone at the apple store.
    Just because you dried doesn't mean that there wasn't any damage done.

  • Please help me make my Macbook air play sound?

    Hello all!
    My Macbook air doesn't play sound anymore. It originally started with when I plugged in my HDMI cord to play on my LCD TV and it wouldn't work. Then I started fiddling with the settings and got it to work for a second. Then with a little more fiddling, somehow managed to turn off internal speakers. The volume is grey with no controls. If I adjust volume with keyboard, the cross out sign shows. I just would love to get some music coming out of my laptop again, and if I could get the HDMI to work too, that would be bonus!!

    Try doing an SMC reset     http://support.apple.com/kb/HT3964    Then go into system prefs/sound/output and makes sure internal speakers are highlighted, if they aren't click on them

  • My Macbook Pro wont play sound through Mini DisplayPort to HDMI adapter on toshiba television anymore. The sound plays through sony or samsung television, but not toshiba television.

    I have a Macbook Pro early 2011 running on mountain lion version 10.8.2. A while back, i purchased a mini display port thru HDMI port so i could watch dvds on my toshiba television. it all worked great for a while, then the sound just stopped working. At first, I thought the mini display port connector must have broke, until I plugged it into a sony television and it worked. I also tried using it through a samsung television and it worked just fine. Why does it not work through the toshiba television anymore? The picture works fine, but the sound does not come thru the television anymore. My mac is set to play sound thru the HDMI port and it doesnt. When i switch it to built in internal speakers, the sound comes thru my mac, but when i switch it, no sound comes out. Any help would be greatly appriciated. Thank you!

    I am still waiting to receive a response from them, but i dont think they'll be much help. the television still works fine and all of the ports on the back, including both HDMI ports, work perfectly.

  • Won't play sound when on the internet

    Just recently my HP 2000 Notebook PC will not play sound that comes from the internet. When i play music or DVD's on my computer I can hear them perfectly. The minute I get on the internet to watch a video or a movie or even video chat I can't hear any sound. I've tried resetting the computer to see if maybe that helped but it didn't. Also, when you go to the control panel to test the speakers they work fine. Also, when I plug in my headphones the sound won't play through those either. Any help would be greatly appreciated.

    Hello, lrc2. 
    Thank you for visiting Apple Support Communities.
    Here is an article I would recommend taking a look at.  Try all of the steps in this article and if you are still experiencing the issue, see step 9.
    iPhone: No sound or distorted sound from speaker
    http://support.apple.com/kb/ts5180
    Cheers,
    Jason H.

  • Can I have a mouse-over function to play sound?

    Hello all,
    I have a flash graphic here www.stainlessrhino.com top left
    corner. What I would like is for the graphic to play (soundless as
    it does now) when the page is loaded, however, if the user mouse
    over the swf a sound would play once. How would I accomplish this?
    Is it possible?
    Thank you!

    There are several ways to do this. The easiest way is to
    attach the sound to the graphic. Do this by editing the object you
    want, create a layer called sounds. Click on the first frame you
    want the sound to play in, press F6 to create a keyframe. Click in
    that keyframe and look in the Properties window. In the box labeled
    "Sound:" (go figure) you select the sound you want to play.
    If you are using a roll-over listener you can use the
    Sound.play() method to play the sound in the function. AS3.0
    example:
    myGraphic.addEventListener(MouseEvent.ROLL_OVER,
    myOverFunction);
    function myOverFunction(event:MouseEvent):void{
    play.sound(mySound);
    I recommend searching for "Playing Sounds" in the help
    documentation (F1).

Maybe you are looking for

  • Having problem with import via dblink

    this is the import command: impdp schemas=g2log network_link=HS5 directory=DATA_PUMP_DIR logfile=g2loggblink.log CONTENT=data_only here are the error messages that I am getting: Connected to: Oracle Database 10g Enterprise Edition Release 10.2.0.3.0

  • Dreamweaver 8.0.2 "Put" Issue with WebDav

    Dreamweaver 8.0.2 "Put" Issue with WebDav In Dreamweaver: I am able to see all of the files in the local and I can see all of the files in the remote. So here is the kicker.... Dreamweaver is only allowing me "Read" access" in the remote view. When I

  • Creation of Purchase Order soon after Relase or Save of Process Order

    Hi, I have a requirement wherein client wants Purchase Order needs to be created soon after Relase or during Saving of Process Order. How this can be done..Is there any standard way or enhancement options. If enhancement how to go about it?

  • Problem with text written on a image

    Hi , I'm new to PSE9. I have a plain image and I want to write some text on it. ok but when I do this the text is does not look right. Its not sharp enough. The definition of the lettersis not brilliant . Also how do you put bullet points on the imag

  • TS4006 can i use find iphone on windows pc using icloud

    I want to know if i can use find iphone on my windows pc via the icloud....and if so how do i do it....i have icloud on my pc and im set up on my ipad....