java - 尝试在我的 ActionListener 中添加播放音频方法

标签 java class user-interface audio actionlistener

我试图将 play 方法放入 Audioapp 类中的 ActionListener 中,我尝试将其放入但出现错误。

我已阅读 ActionListener 上的 javadoc,但找不到它

这是我的音频:

public class Audioapp extends JApplet // find out how to implement play method into action listener?
{
    public class Sound // Holds one audio file
    {
        private AudioClip song; // Sound player
        private URL songPath; // Sound path
        Sound(String filename)
        {
            try
            {
                songPath = new URL(getCodeBase(),"G:\\Uni\\Programming\\Rolling assignements\\Week0\\Programming week21");  // This is the place were im getting error
                song = Applet.newAudioClip(songPath); // Load the Sound
            }
            catch(Exception e){e.printStackTrace();} 
        }
        public void playSound()
        {
            song.play(); // Play
        }
    }
}

这是我的actionListener:

class PlayStoHandler implements ActionListener {
    public void actionPerformed(ActionEvent event) {
        String computerRand = sps.computerChoice();
        txtComputerRand.setText(computerRand);
        String result = sps.play(Sps.ROCK);
        txtResult.setText(result);

        scis.setVisible(false);
        open.setVisible(false);
        stone.setVisible(true);
        pap.setVisible(false);
        win.setVisible(false);
        none.setVisible(false);
        lose.setVisible(false);

        if (result == "User Wins"){
            win.setVisible(true);

                              song.play(); // here i tried putting the song.play in this if section, the error I got was "song cannot be resolved"
        }

        else if (result == "Draw"){
            none.setVisible(true);
        }
        else {
            lose.setVisible(true);
        }
    }

我是初学者,所以这很可能是一个非常愚蠢的基本错误

如有任何帮助,我们将不胜感激

最佳答案

songPath = new URL(getCodeBase(),"G:\\Uni\\Programming\\Rolling assignements\\Week0\\Programming week21");

URL 构造函数期望第二个字符串表示相对 URL,而您已经输入了文件路径。 URL 始终带有正斜杠,并且基于 file: 的 URL 没有什么意义(WAV 托管在您的网站上,而不是最终用户的 HD 上)。

如果小程序是由站点根目录下的 HTML 加载的,且 HTML 中没有声明 codebase,并且 wav 名为 moo.wav 且位于在名为 Week0/Programming week21 的子目录中,正确的路径是:

songPath = new URL(getCodeBase(),"Week0/Programming week21/moo.wav");

但为了让事情变得更简单,至少目前,请将 HTML、小程序剪辑放在同一目录 并使用:

songPath = new URL(getCodeBase(),"moo.wav");

关于java - 尝试在我的 ActionListener 中添加播放音频方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15481372/

相关文章:

java - 在我制作的乒乓球游戏中,我不能同时移动两个 Racket

java - Java 模式解析

javascript - Setter/Getter 对此

c++ - Qt - moc 文件相关错误

c# - 如何将我的标题基于窗口的宽度 W/O 不必重复编写相同的代码

java - 更改 jScrollPane 的一侧并更改大小

java - 如何更改HashMap中键的值?

Java 客户端服务器聊天在转换为 byte[] 时用方 block 填充字符串

php - 如何将sql与php代码分开

python - 处理像字典这样的对象