2012-07-10 53 views
1

好吧,即時通訊工作,我的程序,將播放一首歌曲,一旦點擊一個按鈕,我有代碼下來,我的音頻播放按鈕時單擊,但現在唯一的問題是,我的程序是完全瘋狂只需點擊按鈕即可播放音頻!該程序只是凍結音頻繼續播放,但該程序不會執行其他功能!我究竟做錯了什麼?我該如何解決它?如何正確添加聲音?

繼承人的動作監聽器按鈕的代碼

在myFrame.java

sound sound = new sound(); 
private File pokemonBattle = new File(".\\audio\\"+"sound.wav"); 


private void dualButtonActionPerformed(java.awt.event.ActionEvent evt)  
    {           
    // TODO add your handling code here: 
    for (int i = 0; i<1; i++){ 
    c = deck.getNextCard(); 
    p1hand[i] = c; 
    p1.setCard(c);     //ignore all this 
    c = deck.getNextCard(); 
    p2hand[i] = c; 
    p2.setCard(c); 
    } 

    pokemon1.setEnabled(true); 
    pokemon2.setEnabled(true); 
    pokemon1.setIcon(p1hand[0].getImage()); //ignore all this as well 
    pokemon2.setIcon(p2hand[0].getImage()); 
    textArea.setText("Pokemon 1:"+p1hand[0].toString()+"\nPokemon 2: 
"+p2hand[0].toString()); 
    p1ResultLabel.setText(""); 
    p2ResultLabel.setText(""); 

     //this is where im calling my audio 
    sound.playAudio(pokemonBattle);//this is where im calling my play audio method 

} 

sound.java在那裏我有playAudio()

import java.io.File; 
import javax.sound.sampled.*; 



public class sound { 

public void playAudio(File sf){ 
    AudioFormat audioFormat; 
    AudioInputStream audioInputStream; 
    SourceDataLine sourceDataLine; 

    try 
    { 
     audioInputStream = AudioSystem.getAudioInputStream(sf); 
     audioFormat = audioInputStream.getFormat(); 
     System.out.println(audioFormat); 

     DataLine.Info dataLineInfo = new 
    DataLine.Info(SourceDataLine.class,audioFormat); 

     sourceDataLine =(SourceDataLine)AudioSystem.getLine(dataLineInfo); 

     byte tempBuffer[]=new byte[100000]; 
     int cnt; 
     sourceDataLine.open(audioFormat); 
     sourceDataLine.start(); 
     while((cnt=audioInputStream.read 
        (tempBuffer,0,tempBuffer.length))!=-1){ 
      if(cnt>0){ 
       sourceDataLine.write(tempBuffer,0,cnt); 
      } 

     } 

    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
     System.exit(0); 
     } 
    } 

} 

回答

1

您需要在播放音頻一個單獨的線程。該程序無響應,因爲它在event dispatch thread上播放音頻,而不是繪製UI並響應用戶交互。

代替:

sound.playAudio(pokemonBattle); 

做:

Thread t = new Thread(new SoundPlayer(sound, pokemonBattle); 
t.start(); 

也:

public class SoundPlayer implements Runnable 
{ 
    private final sound sound; 
    private final File soundFile; 

    public SoundPlayer(sound sound, File soundFile) 
    { 
     this.sound = sound; 
     this.soundFile = soundFile; 
    } 

    public void run() 
    { 
     sound.playAudio(soundFile); 
    } 
} 
+0

我很抱歉,但我完全困惑我究竟會在一個單獨的線程播放音頻? – 2012-07-10 02:12:20

+0

謝謝你約瑟夫。得到它的工作! – 2012-07-10 03:00:09

0

約瑟夫是正確的。但在這種情況下,問題是

while((cnt=audioInputStream.read 
        (tempBuffer,0,tempBuffer.length))!=-1){ 
      if(cnt>0){ 
       sourceDataLine.write(tempBuffer,0,cnt); 
      } 

     } 

你while循環將無限運行因此凍結你的應用程序。由於您正在讀取和寫入整個緩衝區,因此不需要while循環。在循環之外做這件事,你會沒事的。