如何播放另一个文件的声音

时间:2014-06-16 14:06:38

标签: java audio startup joptionpane

我正在制作游戏并想为我的角色选择页面添加声音。所以我创建了一个播放歌曲的工作java文件,但如何在启动我的角色选择屏幕时播放歌曲文件?

注意: 两个文件都在同一个软件包中。

package comp_sci;

import java.io.*;
import sun.audio.*;

public class PlaySound
{
  public static void main(String[] args) 
  throws Exception
  {
    // open the sound file as a Java input stream
    String gongFile = "music.wav";
    InputStream in = new FileInputStream(gongFile);

    // create an audiostream from the inputstream
    AudioStream audioStream = new AudioStream(in);

    // play the audio clip with the audioplayer class
    AudioPlayer.player.start(audioStream);
  }
}

这是我的声音文件。为了在我的其他程序中使用它,我尝试了下面的代码,但它没有用。

PlaySound winn2 = new PlaySound();

1 个答案:

答案 0 :(得分:1)

在PlaySound类中,创建一个名为playSound的方法,其中包含播放歌曲的代码

public void playSound(String filename) {
    InputStream in = new FileInputStream(filename);
    AudioStream audioStream = new AudioStream(in);
    AudioPlayer.player.start(audioStream);
}

要在启动时调用此方法,请使用以下代码

PlaySound winn2 = new PlaySound();
winn2.playSound("music.wav");

您的代码无法正常工作的原因是,如果您从该类开始,则使用main()方法。如果要运行代码,则需要创建类的实例,或使用静态方法。

相关问题