簡體   English   中英

Java沒有為按鈕播放聲音

[英]Java no sound played for button

當我點擊按鈕時,我創建了一個播放聲音的class

這是代碼:

public void playSound()
    {
        try 
        {
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("beep-1.wav"));
            Clip clip = AudioSystem.getClip( );
            clip.open(audioInputStream);
            clip.start( );
        }
        catch(Exception e)
        {
            System.out.println("Error with playing sound.");
        }
    }

當我想將它實現到ButtonListener方法中時,似乎沒有播放聲音。

這里是ButtonListener代碼:

private class ButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e) 
        {
            if (replayButton == e.getSource()) 
            {
                playSound();
            }
        }
    }

代碼有什么問題?

編輯:

基本上我正在嘗試創建一個簡單的記憶游戲,我想在點擊時為按鈕添加聲音。

解決了 :

好像我從Soundjay下載的音頻文件有問題,因此無法播放音頻文件。 @ _ @

采用

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        playSound();
    }
});

這應該工作:

public class Test extends JFrame {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        JButton button = new JButton("play");
        button.addActionListener(new  ActionListener() {
        public void actionPerformed(ActionEvent e) {
                playSound();
        }});
        this.getContentPane().add(button);
        this.setVisible(true);
    }

    public void playSound() {
        try {
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("beep.wav"));
            Clip clip = AudioSystem.getClip( );
            clip.open(audioInputStream);
            clip.start( );
        }
        catch(Exception e)  {
            e.printStackTrace( );
        }
    }
}

請注意,在播放文件期間,GUI將不負責任。 在你的監聽器中使用Joop Eggen的方法來糾正這個問題。 它會異步播放文件。

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        playSound();
    }
});

任何堆棧跟蹤,請??? 你有沒有添加監聽器按鈕???

無論如何,當針對跨平台時,標准方式會有一些錯誤。 請訪問http://www.oracle.com/technetwork/java/javase/tech/index-jsp-140239.html使用Java Media Framework。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM