[英]Add sound to my basic 'Sound Adventure' game
如何為我的基本“聲音冒險”游戲添加聲音?
我是初學者,我想制作一個基本的聲音冒險游戲。 (是的,你沒聽錯,聲音冒險。)
我知道 Java 的基礎知識,我可以編寫文本冒險的代碼,但我還不知道 Sound 在 Java 中是如何工作的。 我在互聯網上看過教程,但它們似乎不起作用。 我准備改變我的聲音格式。 (目前是 .mp3)另外,我在 Eclipse Kepler 中使用 JDK 7。 (如果有幫助的話。)
到目前為止,這是我的代碼:
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!");
}
}
}
一個簡單的谷歌搜索就有大量的資源。
使用 JavaFX 框架
只需使用AudioClip 的一個實例。 這個非常適合只播放單個短音。
AudioClip plonkSound = new AudioClip("http://somehost/path/plonk.aiff");
plonkSound.play();
使用標准 Java API
標准 Java API 有點痛苦,我沒有任何經驗,但是這段代碼在這個相關問題上有 60 多個贊成票。
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.