2012-11-22 55 views
1

我的設置是如下:Java的TargetDataLine的和SourceDataLine的重新不起作用

我有一個Java小程序在錄製和播放音頻瀏覽器中運行。

我的問題是:

當我刷新瀏覽器時,SourceDataLine的正確刷新後重新開放,而TargetDataLine的不重啓本身。

public void init() { 
    try { 
     DataLine.Info sourceDataLineInfo = new DataLine.Info(
       SourceDataLine.class, audioFormat); 
     DataLine.Info targetDataLineInfo = new DataLine.Info(
       TargetDataLine.class, audioFormat); 

     // Setup a Line.Info instance specifically of the TargetDataLine class. 
     Line.Info targetDLInfo = new Line.Info(TargetDataLine.class); 
     Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo(); 
     Mixer currentMixer = null; 

     try { 

      for(int cnt = 0; cnt < mixerInfo.length; cnt++) { 
       // Get a temporary instance of the current mixer 
       currentMixer = AudioSystem.getMixer(mixerInfo[cnt]); 

       if(currentMixer.isLineSupported(targetDLInfo)) { 
        Log.log("Found mixer:" + mixerInfo[cnt].getName()); 
        System.out.println(mixerInfo[cnt].getName()); 
        break; 
       } 

       //currentMixer = null; 

      } 
     } catch(Exception e) { 
      Log.log("Found no mixer"); 
     } 

     if(!Client.refresh) { 

      try { 
       sourceDataLine = (SourceDataLine) AudioSystem 
         .getLine(sourceDataLineInfo); 
      }catch(Exception e){ 
       Log.log("Unable to stream audio not starting playthread"); 
      } 

      play = new PlayThread(); 

      if(sourceDataLine != null) { 
       sourceDataLine.open(audioFormat); 
       sourceDataLine.start(); 

       play.start(); 
      } 


       try { 
        targetDataLine = (TargetDataLine) currentMixer.getLine(targetDataLineInfo); 
       }catch(Exception e) { 
        connection.addMessage("[WARNING] Your microphone is not working."); 
       } 


      capture = new CaptureThread(); 

      if(currentMixer != null) { 
       if(targetDataLine != null) { 

         targetDataLine.open(audioFormat); 
         targetDataLine.start(); 
         capture.start(); 
       } 
      }else { 
       connection.addMessage("[WARNING] No compatible microphone found."); 
       Log.log("Not able to record data since no mixer was found"); 
      } 

     } else { 
      sourceDataLine.open(audioFormat); 
      sourceDataLine.start(); 
      targetDataLine.open(audioFormat); 
      targetDataLine.start(); 
     } 

     } catch (Exception e) { 
      Log.log("An exception occured when trying to startup the audio"); 
     } 

} 

我的代碼有什麼問題?

+0

你正確地關閉了資源上的'停止()'或'破壞()'?爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 –

回答

1

正如安德魯說,你需要關閉打開的SourceDataLine和TargetData線。在刷新瀏覽器時,init()會再次被調用,因爲它是小程序的新實例。如果數據線已經打開,並且您試圖再次打開它,則會引發異常:「線不受支持:audioFormat」。由於每次結束applet實例時都會調用destroy(),因此需要處理其中打開的datalines的關閉。