球在無限循環中上下移動。聲音應該用於每個動作。但它每5-6次運動都會發揮。爲什麼會發生?聲音持續時間少於1秒。在代碼中,在循環的每次迭代中都有3秒的睡眠時間。但是,將睡眠持續時間改爲6秒即可達到所需的效果。java動畫聲音不能正常播放
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import sun.audio.*;
import java.io.*;
public class dabble {
private boolean z=false;
private int x=10;
private int y=10;
private JFrame frame;
private JLabel label;
private mypanel panel;
private JButton b1;
private JButton b2;
public static void main (String[] args) throws Exception
{
dabble dab = new dabble();
dab.start();
}
void start()
{
frame = new JFrame();
label = new JLabel();
panel = new mypanel();
b1= new JButton("Start");
b2= new JButton("Stop");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1.addActionListener(new al1());
b2.addActionListener(new al2());
frame.getContentPane().add(BorderLayout.NORTH,b1);
frame.getContentPane().add(BorderLayout.SOUTH,b2);
frame.getContentPane().add(BorderLayout.CENTER,panel);
frame.getContentPane().add(BorderLayout.EAST,label);
frame.setSize(600,600);
frame.setVisible(true);
}
class al1 implements ActionListener{
public void actionPerformed(ActionEvent event){
if (z==false)
{
class myrun implements Runnable{
public void run(){
z=true;
while(z==true)
{
y=510-y;
panel.repaint();
try
{
InputStream in=new FileInputStream("hit.wav");
AudioStream as=new AudioStream(in);
AudioPlayer.player.start(as);
Thread.sleep(3000);
}
catch(Exception Ex){}
}
}
}
Runnable myjob = new myrun();
Thread mythread = new Thread(myjob);
mythread.start();
}
}
}
class al2 implements ActionListener{
public void actionPerformed(ActionEvent event){
z=false;
}
}
class mypanel extends JPanel {
public void paintComponent (Graphics g){
g.setColor(Color.white);
g.fillRect(0,0,this.getWidth(),this.getHeight());
int red = (int) (Math.random()*255);
int green = (int) (Math.random()*255);
int blue = (int) (Math.random()*255);
Color c1 = new Color(red,green,blue);
g.setColor(c1);
g.fillOval(x,y,20,20);
}
}
}
我試着運行代碼,但用javax.sound.sampled SourceDataLine,並得到了同樣的錯誤。將代碼移到構造函數中並沒有多大幫助。儘管場合下降到了30分之一的範圍,但仍然有些聲音來得太遲。非常好奇。 – 2012-02-16 20:31:10