【问题标题】:Add sound to my basic 'Sound Adventure' game为我的基本“声音冒险”游戏添加声音
【发布时间】:2014-01-13 06:04:41
【问题描述】:

如何在基本的“声音冒险”游戏中添加声音?

我是一个初学者,我想做一个基本的声音冒险游戏。 (是的,你没听错,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!");
    }
}
}

【问题讨论】:

  • 您可以从Sound 线索开始,或者如果您想坚持使用 MP3,请查看JLayer by JavaZoom。尝试一些东西,看看有什么效果..

标签: java eclipse audio javafx


【解决方案1】:

一个简单的 Google 搜索就有大量的资源。

使用 JavaFX 框架

只需使用AudioClip 的实例。这一款非常适合只播放单个短音。

AudioClip plonkSound = new AudioClip("http://somehost/path/plonk.aiff");
plonkSound.play();

使用标准 Java API

标准 Java API 有点痛苦,我没有任何经验,但这段代码在 related question 上有 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();
}

【讨论】:

    猜你喜欢
    • 2016-08-25
    • 2023-03-11
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    相关资源
    最近更新 更多