1

私は利用可能なコードを使用しようとしています: How can I play sound in Java? しかし、これは新しいアカウントであり、評判が 1 つしかないため、そこに質問を投稿することはできません。

元のコード:

  public static synchronized void playSound(final String url) {
  new Thread(new Runnable() { // the wrapper thread is unnecessary, unless it blocks on the Clip finishing, see comments
  public void run() {
    try {
      Clip clip = AudioSystem.getClip();
      AudioInputStream inputStream = AudioSystem.getAudioInputStream(Main.class.getResourceAsStream("/path/to/sounds/" + url));
      clip.open(inputStream);
      clip.start(); 
    } catch (Exception e) {
      System.err.println(e.getMessage());
    }
  }
}).start();
}

これは私のコードです:

package sound_test;
import javax.sound.sampled.*;

public class Main {

public static synchronized void playSound(final String url) {
new Thread(new Runnable() {
  public void run() {
    try {
      Clip clip = AudioSystem.getClip();
      AudioInputStream inputStream = AudioSystem.getAudioInputStream(Main.class.getResourceAsStream("/path/to/sounds/" + url));
      clip.open(inputStream);
      clip.start();
    } catch (Exception e) {
      System.err.println(e.getMessage());
    }
  }
}).start();
}

public static void main(String[] args) {
    // TODO code application logic here
    playSound("C:\\warning_test.wav");
}

}

コードを実行すると、出力として「null」が表示され、音が出ませんでした。ファイル名とパスを確認しましたが、正しいです。

スクリーンショット:

http://puu.sh/pkYo

http://puu.sh/pkZl

前もって感謝します。

4

2 に答える 2

0

あなたができる

AudioInputStream inputStream=AudioSystem.getAudioInputStream(new File(url));

後に遅延も追加しますclick.start(); i.e Thread.Sleep(4000);

または、オーディオサンプル全体を確実に再生したい場合は、次のような単純なスニペットを使用できます

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

public class Main  implements LineListener {
private boolean done = false;
public  void update(LineEvent event) {
    if(event.getType() == LineEvent.Type.STOP || event.getType() == LineEvent.Type.CLOSE) {
      done = true;
    }
}

public void waitonfinish() throws InterruptedException {
   while(!done) {
       Thread.sleep(1000);
   } 
}
public static  void playSound(final String url) {

    try {
      Clip clip = AudioSystem.getClip();
      AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File(url));
      Main control = new Main();
      clip.addLineListener(control);
      clip.open(inputStream);
      clip.start();
      control.waitonfinish();

    } catch (Exception e) {
      System.err.println(e.getMessage());
    }
  }

public static void main(String[] args) {
    // TODO code application logic here
    playSound("C:\\warning_test.wav");   
 }
}

`

于 2012-04-13T05:00:13.053 に答える