简体   繁体   中英

Can't play sound in java using clip

I want to play some sound in java using this code bellow. That sound is in WAV format so I think that this code should work fine, but instead of playing sound it simply does nothing. There is no even error on my console. So can someone help me to make this code play sound. (this sound is included inside one package in my src file)

 public static void main(String[] args) {

 new Thread(new Runnable() {

        @Override
        public void run() {

            try {

                Clip clip = AudioSystem.getClip();

                File file = new File("C:\\Users\\Jovan\\Desktop\\song.wav");

                AudioInputStream inputStream = AudioSystem.getAudioInputStream(file);

                clip.open(inputStream);

                clip.start();

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    });
 }

You have to wait for the clip to play and end. You can also create some Listener but that's more complicated. When the clip finishes playing (isActive() is false) you end.

public class P {

 public static void main(String[] args) {

 new Thread(new Runnable() {

        @Override
        public void run() {

            try {

            System.out.println("started");

                Clip clip = AudioSystem.getClip();

                File file = new File(".......................wav");

                AudioInputStream inputStream = AudioSystem.getAudioInputStream(file);

                clip.open(inputStream);

                clip.start();

                while(clip.isOpen()) {
                  try { Thread.sleep(2000); } catch(InterruptedException ie) {}
                  if(!clip.isActive()) break;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }).start();
 }

 }

You have just started this thread, so create an object:

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

class x {
    public static void main(String[] args) {

        Thread b= new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Clip clip = AudioSystem.getClip();
                    File file = new File("G:/skit/msg.wav");
                    AudioInputStream inputStream = AudioSystem.getAudioInputStream(file);
                    clip.open(inputStream);
                    clip.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
        b.start();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM