2013-10-15 99 views
0

即時嘗試在java中創建一個類,播放某些聲音,但聲音在隨機時刻停止,而不是結束。爲什麼這樣做?提前致謝!.wav文件的聲音在隨機時間停止在JAVA

這裏是我的代碼:

import java.io.File; 

import javax.sound.sampled.AudioInputStream; 
import javax.sound.sampled.AudioSystem; 
import javax.sound.sampled.Clip; 
import javax.sound.sampled.Line; 
import javax.sound.sampled.LineEvent; 
import javax.sound.sampled.LineListener; 
import javax.swing.JDialog; 
import javax.swing.JFileChooser; 

public class CoreJavaSound extends Object implements LineListener { 
File soundFile; 

JDialog playingDialog; 

Clip clip; 

public static void main(String[] args) throws Exception { 
PlayBow(); 

} 

public CoreJavaSound(String fileName) throws Exception { 
JFileChooser chooser = new JFileChooser(); 

soundFile = new File(fileName); 


System.out.println("Playing " + soundFile.getName()); 

Line.Info linfo = new Line.Info(Clip.class); 
Line line = AudioSystem.getLine(linfo); 
clip = (Clip) line; 
clip.addLineListener(this); 
AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile); 
clip.open(ais); 
clip.start(); 
} 

@Override 
public void update(LineEvent le) { 
LineEvent.Type type = le.getType(); 
if (type == LineEvent.Type.OPEN) { 
    System.out.println("OPEN"); 
} else if (type == LineEvent.Type.CLOSE) { 
    System.out.println("CLOSE"); 
    System.exit(0); 
} else if (type == LineEvent.Type.START) { 
    System.out.println("START"); 
    playingDialog.setVisible(true); 
} else if (type == LineEvent.Type.STOP) { 
    System.out.println("STOP"); 
    playingDialog.setVisible(false); 
    clip.close(); 
} 
} 

public static void PlayBow() throws Exception 
{ 
CoreJavaSound s = new CoreJavaSound("Bow.wav"); 
} 
} 

一切工作正常,除了一個事實,即聲音停止後樣1的第二工作(而該文件是5秒)...

回答

1

剪輯在後臺線程上啓動,不是阻塞呼叫。它在後臺播放。所以程序終止而不允許剪輯完成播放。

嘗試這樣:

... 
    static boolean running = false; 

    public static void main(String[] args) throws Exception { 
    playBow(); 
    while(running) { 
     Thread.sleep(200); 
    } 
    } 
    ... 
    @Override 
    public void update(LineEvent le) { 
    LineEvent.Type type = le.getType(); 
    if (type == LineEvent.Type.OPEN) { 
     running = true; 
     System.out.println("OPEN"); 
    } else if (type == LineEvent.Type.CLOSE) { 
     System.out.println("CLOSE"); 
    } else if (type == LineEvent.Type.START) { 
     System.out.println("START"); 
     playingDialog.setVisible(true); 
    } else if (type == LineEvent.Type.STOP) { 
     System.out.println("STOP"); 
     playingDialog.setVisible(false); 
     clip.close(); 
     running = false; 
    } 
    } 

注意,該樣本是不是解決這個問題的最佳解決方案。這只是一個例子。

+0

這工作得很好!所以我不想這麼想:p非常感謝你! –