我终于在我正在制作的这个游戏中整合了一个配乐,但它只有一首歌。我怎么能让这个循环播放一些歌曲以扩展我的配乐?
try{
AudioInputStream stream;
AudioFormat format;
DataLine.Info info;
Clip clip;
stream = AudioSystem.getAudioInputStream(new File("Spring.wav"));
format = stream.getFormat();
info = new DataLine.Info(Clip.class, format);
clip = (Clip) AudioSystem.getLine(info);
clip.open(stream);
//plays the song
clip.start();
//keeps the song on repeat
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
catch (Exception e) {
}
您的代码实际上不会播放任何声音,因为线程会立即关闭。在我的例子中,我添加了一个thread.sleep命令。下一个问题:摆脱clip.loop行,因为你不想这样做。我的版本中的想法是将玩家分成它自己的类,它将从主游戏中播放。这样,您可以让播放器的一个实例播放一次曲调,然后以您想要的任何方式进行切换。我选择在示例中依次播放每个wave文件,但如果您愿意,可以随机播放或整个波形文件:
班级:
package scrapAudioClips;
import java.io.File;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
public class AudioPlayer {
public void play(String filename) {
//The filename and time to play are passed into the method.
try {
AudioInputStream stream1;
AudioFormat format = null;
DataLine.Info info;
Clip clip;
stream1 = AudioSystem.getAudioInputStream(new File(filename));
format = stream1.getFormat();
info = new DataLine.Info(Clip.class, format);
clip = (Clip) AudioSystem.getLine(info);
clip.open(stream1);
//These next two lines will get the length of the wave file for you...
long frames = stream1.getFrameLength();
double durationInSeconds = (frames+0.0) / format.getFrameRate();
// plays the song
clip.start();
// clip.loop(Clip.LOOP_CONTINUOUSLY); You don't need this anymore.
Thread.sleep((long)(durationInSeconds * 1000)); // This allows you to actually hear the audio for the time in seconds..
} catch (Exception e) {
System.out.println("File not recognized");
}
}
}
主要:
package scrapAudioClips;
public class scrapAudio {
public static void main(String[] args) {
AudioPlayer player = new AudioPlayer();
//you may play sequentially or in any random order you want with any loop structure you like...
player.play("Alesis.wav"); //You just pass the file name in...
player.play("wavefile1.wav");//Make your own playlist class as an array...
player.play("wavefile2.wav");//loop it randomly or in sequence...
}
}