Java中没有播放声音的按钮 [英] Java no sound played for button

查看:356
本文介绍了Java中没有播放声音的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个来播放声音,当我点击的按钮。

I have created a class to play the sound when I click the buttons.

下面是code:

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 方法,它看起来像没有播放声音。

When I want to implement it into the the ButtonListener method, it's seem like no sound is played.

下面的 ButtonListener code:

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

什么是错的code?

What's wrong with the code?

编辑:

基本上我试图创建一个简单的记忆游戏,我想点击时添加声音的按钮。

Basically I'm trying to create a simple memory game, and I want to add sound to the buttons when clicked.

解决:

好像音频文件,我从 Soundjay 下载有问题,因此,音频文件不能播放。 @ _ @

Seems like the audio file I downloaded from Soundjay got problem, and hence, the audio file can't be played. @_@

推荐答案

这应该工作:

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( );
        }
    }
}

请注意,您的文件的播放过程中,图形用户界面将不RESPONSABLE。使用来自乔普·埃根的办法在你的听众来纠正。它会播放该文件异步的。

Note that during the play of your file, the GUI will be not responsable. Use the approach from Joop Eggen in your listener to correct this. It will play the file asynchronous.

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

这篇关于Java中没有播放声音的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆