即使我的代码基于一个工作示例,我的 wav 声音也不会播放。我不知道我的错误在哪里。我在互联网上找到了这个代码示例:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.io.*;
class Testing extends JFrame implements ActionListener
{
JButton btn = new JButton("Play Sound");
File wavFile = new File("c:\\Windows\\media\\ding.wav");
AudioClip sound;
public Testing()
{
setSize(300,100);
setLocation(400,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel jp = new JPanel();
btn.addActionListener(this);
jp.add(btn);
getContentPane().add(jp);
pack();
try{sound = Applet.newAudioClip(wavFile.toURL());}
catch(Exception e){e.printStackTrace();}
}
public void actionPerformed(ActionEvent ae){sound.play();}
public static void main(String args[]){new Testing().setVisible(true);}
}
它工作正常。我创建了一个 WavReader 类,它将加载 AudioClip 声音。我的按钮有一个 WavReader 属性。我想要做的是通过我的 Button 的 MouseEnetered 事件播放 WavReader 声音。这是我的 WavReader 课程:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.io.*;
public class WavReader {
File wavFile;
public AudioClip sound;
public WavReader(String file) {
wavFile = new File(file);
try {
sound = Applet.newAudioClip(wavFile.toURL());
}
catch(Exception e) {
e.printStackTrace();
}
}
public void playSound() {
sound.play();
}
public void stopSound() {
sound.stop();
}
}
这是我的个性化按钮的块:
public class ButtonMenu extends JButton{
public ButtonMenu() {
private WavReader reader = new WavReader("blabla.wav");
addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
setForeground(Color.red);
reader.playSound();
}
public void mouseExited(MouseEvent e) {
setForeground(Color.white);
reader.stopSound();
}
} // end MouseAdaptater
); // end MouseListener
}
}
运行时没有错误,但是我的声音不会播放。你能告诉我做错了什么吗?
我能看到的唯一区别是我的 AudioClip 属性不是任何 JFrame 的一部分,而是我的 WavReader 类的一部分,它是我的 Button 的一部分。