【问题标题】:How to play a sound that is another file如何播放另一个文件的声音
【发布时间】:2014-08-06 09:23:24
【问题描述】:

我正在制作游戏并想为我的角色选择页面添加声音。所以我创建了一个可以播放歌曲的 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();

【问题讨论】:

    标签: java audio startup joptionpane


    【解决方案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() 方法。如果要运行代码,要么需要创建类的实例,要么使用静态方法。

    【讨论】:

    • 我不明白
    • main 方法仅在您从该文件开始时执行。如果您按照您在问题中所做的操作,则 main() 方法将不会执行。你必须把你的代码放在一个公共方法中,然后像我的问题一样从你的菜单代码中调用它
    • 所以我要删除我的音乐代码并粘贴你写的内容吗?但是我在现场文件名中填写什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    • 2010-09-12
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多