[英]Play audio files in Java
I am trying to play a simple audio file which is in the same directory near the class file. 我正在尝试播放一个简单的音频文件,该文件位于类文件附近的同一目录中。 I tried many examples from the internet, but all the others gave me errors which I couldn't even understand. 我从互联网上尝试了许多示例,但是所有其他示例都给了我我什至无法理解的错误。
Then I found this, and I am using it now. 然后我找到了,现在正在使用它。
There are neither compile errors nor runtime errors. 既没有编译错误也没有运行时错误。 But the problem is I cannot hear any noise. 但是问题是我听不到任何声音。
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
class A{
public static void main (String[]args){
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("abc.wav").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch(Exception ex) {
System.out.println("Error with playing sound.");
}
}
}
Please note that my system volume is 80%, and the audio file plays in VLC media player. 请注意,我的系统音量为80%,并且音频文件在VLC媒体播放器中播放。
Starting the audio clip does not block the main method. 启动音频剪辑不会阻止main方法。 So 所以
clip.start();
starts playing and then returns. 开始播放,然后返回。 Now your main method ends and therefore the Java process ends. 现在您的主要方法结束了,因此Java进程结束了。 No sound. 没有声音。
If you do 如果你这样做
clip.start();
Thread.sleep(20000);
you should hear the clip playing for 20 seconds. 您应该会听到剪辑播放了20秒钟。
So for a working program just must make sure that the main thread does not end as long as you want to play the clip. 因此,对于正在运行的程序,只需确保只要要播放剪辑,主线程就不会结束。
Hold the thread for a while until the audio clip plays. 保持螺纹一段时间,直到播放音频剪辑。
long audioPlayTime = 1000; //clip duration in miliseconds.
try {
Thread.sleep(audioPlayTime);
} catch (InterruptedException ex){
//TODO
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.