我试图将 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/