好的,所以我正在制作一款游戏,当你位于不同的地区或出现中断时,音乐会发生变化,就像人工智能一样。
所以我刚刚学会了如何在我的程序中显示音乐,现在我试图让它停止,但我不确定如何做,下面是音乐播放的代码片段,然后我尝试覆盖当 Action 发生时,它会播放新的音乐。
public static void songs(String word) {
String temp = word;
if (temp.equals("start")) {
try {
try {
blah = new FileInputStream("C:/Users/Austin/Desktop/Storage/programimages/game/battle.wav");
} catch (Throwable e) {
e.printStackTrace();
}
AudioStream as = new AudioStream(blah);
AudioPlayer.player.start(as);
System.out.println("going");
} catch (IOException e) {
System.err.println(e);
}
}
if (temp.equals("stop")) {
try {
try {
blah = new FileInputStream("C:/Users/Austin/Desktop/Storage/programimages/game/silence.wav");
} catch (Throwable e) {
e.printStackTrace();
}
AudioStream as = new AudioStream(blah);
AudioPlayer.player.stop(as);
System.out.println("stopping");
} catch (IOException e) {
System.err.println(e);
}
}
}
这是我能找到的唯一可以播放音乐的方法,但如果你们有任何其他建议,请告诉我。
再说一次,我希望有声音效果和音乐,现在所发生的只是播放一首歌,并且在任何情况下都不会停止,直到它达到长度的最后。我希望能够在新歌曲出现时停止播放歌曲,并且允许弹出声音效果。
谢谢! (因为我被困在这个问题上并且现在需要答案,所以我可能会重新发布到一两个以上的 java 站点,以便我可以尽快得到答复,但还是谢谢你!!!!)
编辑代码:(仍然不会停止当前流,任何更多建议表示赞赏)
public static void songs(String word) throws IOException {
String temp = word;
if (temp.equals("go")) {
try {
blah = new FileInputStream("C:/Users/Austin/Desktop/Storage/programimages/game/battle.wav");
} catch (Throwable e) {
e.printStackTrace();
}
AudioStream as = new AudioStream(blah);
AudioPlayer.player.start(as);
System.out.println("going");
}
if (temp.equals("stop")) {
//don't try and do things with a null object!
if (as != null) {
AudioPlayer.player.stop(as);
System.out.println("stopping1");
}
System.out.println("stopping2");
AudioPlayer.player.stop(as);
}
}
最佳答案
当前,您正在 stop 分支中创建一个新的 AudioStream
并使用它调用 stop 方法。这是与当前正在播放的对象不同的对象。尝试将 AudioStream
设为类变量,然后对其调用 stop。
编辑:在包含代码的类的顶部...
class YourClass {
//the class member variable
private AudioStream as;
//[etc...]
在你的起始分支中:
// 'as' has already been defined above
as = new AudioStream(blah);
AudioPlayer.player.start(as);
System.out.println("going");
在你的停止分支中:
try
{
//don't try and do things with a null object!
if (as != null)
{
AudioPlayer.player.stop(as);
}
System.out.println("stopping");
}
catch (IOException e)
{
System.err.println(e);
}
您的方法上的 static
标识符可能会遇到问题 - 如果您从实例化的类中调用它,则不需要它。
关于java - Java 中的音乐(开始/停止),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9668361/