2014-05-11 95 views
0

我想創建一個程序,當按下某個按鈕時播放某個.wav文件。例如,JButton b1, b2, b3分別播放"Music1.wav","Music2.wav""Music3.wav",但一次只能播放一個wav文件。這就是我所做的,它在停止先前剪輯並導致兩個或更多wav文件同時播放時遇到問題。如何一次播放一個.wav文件?

... //imports the important stuff 
public class WAVButtons extends JFrame implements ActionListener 
{ 
    private JButtons b1, b2, b3; 
    private File[] sounds; 

    public WAVButtons() 
    { 
     try 
     { 
       sounds = new File[] 
         {new File("Music1.wav"), 
         new File("Music2.wav"), 
         new File("Music3.wav")}; 
     }catch(Exception e) 
     { 
     } 
     b1 = new JButton("play Music1"); 
     b2 = new JButton("play Music2"); 
     b3 = new JButton("play Music3"); 
     b1.addActionListener(this); 
     b2.addActionListener(this); 
     b3.addActionListener(this); 
     ... //codes for GUI 
    } 

    public void actionPerformed(ActionEvent ae) 
    { 
     if(ae.getSource() == b1) 
     { 
       playMusic1(true); 
       playMusic2(false); 
       playMusic3(false); 
     } 
     else if(ae.getSource() == b2) 
     { 
       playMusic1(false); 
       playMusic2(true); 
       playMusic3(false); 
     } 
     else if(ae.getSource() == b3) 
     { 
       playMusic1(false); 
       playMusic2(false); 
       playMusic3(true); 
     } 
    } 

    public void playMusic1(boolean action) 
    { 
     try 
     { 
      AudioInputStream stream = AudioSystem.getAudioInputStream(sounds[0]); 
      AudioFormat format = stream.getFormat(); 
      DataLine.Info info = new DataLine.Info(Clip.class, format); 
      Clip clip = (Clip)AudioSystem.getLine(info); 
      clip.open(stream); 
      if(action) 
      { 
       clip.start(); 
       clip.loop(Clip.LOOP_CONTINUOUSLY); 
      } 
      else 
       clip.stop(); 
     }catch (Exception e) 
     { 
     } 
    } 

    ... //playMusic2() and playMusic3() looks exactly the same as playMusic1(), except that the 
     //parameter of AudioSystem.getAudioInputStream() is sounds[1] and sounds[2], respectively. 
} 

回答

1

當你調用playMusic1(真),其次是playMusic1(假的),第二個呼叫將創建一個剪輯的新實例,然後停止新的實例。第一個電話創建的第一個實例將繼續播放。您應該堅持對剪輯的引用,以便可以停止。我也冒着去除你的重複代碼的自由。

Clip clip; 

public void actionPerformed(ActionEvent ae) 
{ 
    if(ae.getSource() == b1) 
    { 
      playMusic(0); 
    } 
    else if(ae.getSource() == b2) 
    { 
      playMusic(1); 
    } 
    else if(ae.getSource() == b3) 
    { 
      playMusic(2); 
    } 
} 

public void playMusic(int clipNum) 
{ 
    try 
    { 
     if (clip != null) 
      clip.stop(); 

     if (action) 
     { 
      AudioInputStream stream = AudioSystem.getAudioInputStream(sounds[clipNum]); 
      AudioFormat format = stream.getFormat(); 
      DataLine.Info info = new DataLine.Info(Clip.class, format); 
      clip = (Clip)AudioSystem.getLine(info); 
      clip.open(stream); 
      clip.start(); 
      clip.loop(Clip.LOOP_CONTINUOUSLY); 
     } 
    }catch (Exception e) 
    { 
    } 
}