简体   繁体   English

无法使用剪辑在java中播放声音

[英]Can't play sound in java using clip

I want to play some sound in java using this code bellow.我想使用下面的代码在java中播放一些声音。 That sound is in WAV format so I think that this code should work fine, but instead of playing sound it simply does nothing.那个声音是 WAV 格式,所以我认为这段代码应该可以正常工作,但它没有播放声音,它什么也不做。 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) (此声音包含在我的 src 文件中的一个包中)

 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.当剪辑完成播放(isActive() 为假)时,您就结束了。

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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