如何在基本的“声音冒险”游戏中添加声音?
我是一个初学者,我想制作一个基本的声音冒险游戏。 (是的,您没听错,Sound Adventure。)
我了解Java的基础知识,并且可以编写文本冒险记录,但是我还不知道Sound在Java中如何工作。我在互联网上看过教程,但它们似乎没有用。
我准备更改声音的格式。 (当前为.mp3)
另外,我将JDK 7与Eclipse Kepler一起使用。 (如果有帮助。)
到目前为止,这是我的代码:
package everything;
import java.util.Scanner;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
public class Main {
public static void main(String[] args) {
// Declarations
System.out.println("Please Enter Your Name To Start...");
Scanner temp = new Scanner(System.in);
String name = temp.nextLine();
System.out.println("Okay " + name + ", Let's Get Started!");
System.out.println("Press N To Start The Game...");
while(!"N".equals(temp.nextLine())){
System.out.println("I Asked For The Letter N, Was It So Hard? Try Again!");
}
}
}
最佳答案
简单的Google搜索实际上有大量资源。
使用JavaFX Framework
只需使用AudioClip的实例。这非常适合只播放单个短声音。
AudioClip plonkSound = new AudioClip("http://somehost/path/plonk.aiff");
plonkSound.play();
使用标准Java API
标准Java API有点痛苦,我对此没有任何经验,但是这段代码在related question上有60多个Upvotes。
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();
}
关于java - 向我的基本 'Sound Adventure'游戏添加声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20770328/