简体   繁体   English

如何在 java 中播放 wav 文件?

[英]How to play wav file in java?

I know this is an already asked question, but i cant get no answer我知道这是一个已经提出的问题,但我无法得到答案

i found this way to play the sound:我找到了这种播放声音的方法:

  Clip sound = AudioSystem.getClip();
  sound.open(AudioSystem.getAudioInputStream(new File("path/to/sound")));
  sound.start();

but the problem is i run this code in a gameloop, and i would like to structure it in a way so that i dont need to read the sound from input each time, but already have saved the sound in the memory so i dont have to load it everytime.但问题是我在游戏循环中运行这段代码,我想以某种方式构造它,这样我就不需要每次都从输入中读取声音,但已经将声音保存在 memory 中,所以我不必每次都加载它。

i tried doing something like this:我试着做这样的事情:

 Clip sound = AudioSystem.getClip();
 sound.open(AudioSystem.getAudioInputStream(new File("path/to/sound")));

while(true)
{
 sound.start();


}

also like this也喜欢这个

AudioStream audiostream = AudioSystem.getAudioInputStream(new File("path/to/sound"));
while(true)
{
     Clip sound = AudioSystem.getClip();
     sound.open(AudioSystem.getAudioInputStream(audiostream));
     sound.start();
}

but it doesnt work, or it works only 1 time但它不起作用,或者它只起作用 1 次

Creating an instance variable is a good way to go.创建实例变量是 go 的好方法。

To play the sound again, first set the frame position to the 0th frame or millisecond.要再次播放声音,首先将帧 position 设置为第 0 帧或毫秒。 The play() method always commences from wherever the sound has been stopped. play() 方法总是从声音停止的地方开始。

Thus:因此:

while(true) {
    sound.setFramePosition(0);
    sound.play();
    ...
}

Clip (Java SE 15 & JDK 15) 剪辑(Java SE 15 和 JDK 15)

Playback of an audio clip may be started and stopped using the start and stop methods.可以使用 start 和 stop 方法开始和停止音频剪辑的播放。 These methods do not reset the media position;这些方法不会重置媒体 position; start causes playback to continue from the position where playback was last stopped. start 导致从上次停止播放的 position 继续播放。 To restart playback from the beginning of the clip's audio data, simply follow the invocation of stop with setFramePosition(0), which rewinds the media to the beginning of the clip.要从剪辑的音频数据的开头重新开始播放,只需使用 setFramePosition(0) 调用 stop,这会将媒体倒回到剪辑的开头。

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

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