Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 当我按下几个按钮时,无法播放几个声音_Java_Swing_Audio_Jbutton_Javasound - Fatal编程技术网

Java 当我按下几个按钮时,无法播放几个声音

Java 当我按下几个按钮时,无法播放几个声音,java,swing,audio,jbutton,javasound,Java,Swing,Audio,Jbutton,Javasound,我的java程序中有三个按钮,可以播放三种不同的声音。看看我的代码: import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.io.File; import java.io.IOException; import javax.sound.sampled.*; import java.awt.datatransfer.*; public class VueEditeurEmail exte

我的java程序中有三个按钮,可以播放三种不同的声音。看看我的代码:

    import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.*;
import java.awt.datatransfer.*;

public class VueEditeurEmail extends JFrame implements ActionListener {

    private JPanel container = new JPanel();
    private JPanel containerHaut = new JPanel();
    private JPanel containerAction = new JPanel();
    private JButton boutonEnvoyer = new JButton("Envoi");
    private JButton boutonAnnuler = new JButton("Annuler");
    private JButton contacts = new JButton("Contacts");
    private JButton coller = new JButton("Coller");
    private JTextArea textArea = new JTextArea();
    private ChampsTexte champs1 = new ChampsTexte("Expéditeur :", "");
    private ChampsTexte champs2 = new ChampsTexte("Destinataire :", "");
    private ChampsTexte champs3 = new ChampsTexte("Objet :", "");
    private JOptionPane jop1 = new JOptionPane();
    private JOptionPane jop2 = new JOptionPane();
    private JOptionPane jop3 = new JOptionPane();
    final Clipboard clipboard = container.getToolkit().getSystemClipboard();


    public VueEditeurEmail() {
        this.setTitle("Expéditeur de Message");
        this.setSize(500, 300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);

        containerHaut.setLayout(new BoxLayout(containerHaut, BoxLayout.Y_AXIS));
        containerHaut.add(champs1);
        containerHaut.add(champs2);
        containerHaut.add(contacts);
        containerHaut.add(coller);
        containerHaut.add(champs3);

        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);

        JScrollPane scrollPan = new JScrollPane(textArea);

        container.setLayout(new BorderLayout());
        container.setBackground(Color.white);
        container.add(containerHaut, BorderLayout.NORTH);
        container.add(scrollPan, BorderLayout.CENTER);

        container.add(containerAction, BorderLayout.SOUTH);
        containerAction.add(boutonEnvoyer, BorderLayout.EAST);
        containerAction.add(boutonAnnuler, BorderLayout.WEST);

        contacts.addActionListener(this);
        boutonEnvoyer.addActionListener(this);
        boutonAnnuler.addActionListener(this);
        coller.addActionListener(this);

        this.setContentPane(container);
        this.setVisible(true);

        containerHaut.setBackground(Color.GRAY);
        champs1.setBackground(Color.GRAY);
        champs2.setBackground(Color.GRAY);
        champs3.setBackground(Color.GRAY);
        textArea.setBackground(Color.YELLOW);
        boutonEnvoyer.setBackground(Color.GRAY);
        boutonAnnuler.setBackground(Color.GRAY);

    }

        public void playSound(String soundName){
            try{
                AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundName).getAbsoluteFile( ));
                Clip clip = AudioSystem.getClip( );
                clip.open(audioInputStream);
                clip.start( );
            }catch(Exception ex){
                System.out.println("Erreur lors de la lecture du son");
                ex.printStackTrace( );
            }
        }

    public void actionPerformed(ActionEvent E) {

        if(E.getSource() == boutonEnvoyer){
            playSound("Envoyé.wav");
            Email monEmail = new Email(champs1.getTexte(), champs2.getTexte(), champs3.getTexte(), textArea.getText());
            monEmail.EnvoiSMTP("admpcsrv1.uha.fr", 25);


            ImageIcon img1 = new ImageIcon("Images/succès.png");
            jop1.showMessageDialog(null, "L'Email a bien été envoyé", "Envoi réussi", JOptionPane.INFORMATION_MESSAGE, img1);
            System.exit(0);
        }

        else if(E.getSource() == boutonAnnuler){
            playSound("Annulé.wav");
            ImageIcon img2 = new ImageIcon("Images/annuler.png");
            jop2.showMessageDialog(null, "Appuyer sur OK pour confirmer l'annulation", "Annulation", JOptionPane.INFORMATION_MESSAGE, img2);
            System.exit(0);
        }

        else if (E.getSource() == contacts){
            playSound("OuvertureContacts.wav");
            ImageIcon img3 = new ImageIcon("Images/OuvertureContacts.png");
            jop3.showMessageDialog(null, "Ouverture de la liste des contacts, appuyer sur Ok pour fermer ce popup", "Liste des contacts", JOptionPane.INFORMATION_MESSAGE, img3);
            File file = new File("Fichiers/InfosContacts.xls");
            try{
            Desktop.getDesktop().open(file);
            }catch(IOException e){
            System.out.println("Ouverture du fichier impossible");
            }

        }

        else if (E.getSource() == coller){
            Transferable clipData = clipboard.getContents(clipboard);
            try{
                if(clipData.isDataFlavorSupported(DataFlavor.stringFlavor)){
                String s = (String)(clipData.getTransferData(DataFlavor.stringFlavor));
                champs2.fieldTexte.replaceSelection(s);
                }
            }catch(Exception ufe){}
        }

    }

    public static void main(String[] args) {
        VueEditeurEmail monEditeur = new VueEditeurEmail();

    }
}
当我按下contacts按钮时,OuvertureContacts.wav声音播放良好。但之后,当我按下boutonEnvoyer按钮或BoutonAnnealer按钮时,它们的声音不会播放。。。问题是,我对这三个按钮使用相同的代码,但当我按下一个按钮时,另一个按钮在第一次按下后不会播放声音


我真的很感谢你的帮助,提前谢谢

您的片段引发了几个问题:

Swing GUI对象应仅在上构造和操作

给每个不同的声音提供自己的流和片段;只初始化每个剪辑一次,而不是每次播放该剪辑

AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(…);
Clip clip = AudioSystem.getClip( );
clip.open(audioInputStream);
尽管音响系统在单独的线程中播放剪辑,但您可能希望在单独的线程中定位和启动剪辑;这将最大限度地减少EDT上的延迟并增强活动性

另请参见标签和此相关信息

增编:SSCCE

import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.net.URL;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;

/**
 * @see https://stackoverflow.com/a/17130160/230513
 * @see http://pscode.org/media/
 * @see http://www.soundjay.com/beep-sounds-1.html
 */
public class Test {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Test().display();
            }
        });
    }

    private void display() {
        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLayout(new FlowLayout());
        f.add(new JButton(new SoundAction("Play 1",
            "http://pscode.org/media/leftright.wav")));
        f.add(new JButton(new SoundAction("Play 2",
            "http://www.soundjay.com/button/beep-1.wav")));
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    class SoundAction extends AbstractAction {

        private Clip clip;

        public SoundAction(String name, String location) {
            super(name);
            try {
                URL url = new URL(location);
                AudioInputStream ais = AudioSystem.getAudioInputStream(url);
                clip = AudioSystem.getClip();
                clip.open(ais);
            } catch (Exception e) {
                e.printStackTrace(System.err);
            }
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            // Runnable optional
            Runnable soundPlayer = new Runnable() {
                @Override
                public void run() {
                    try {
                        clip.setMicrosecondPosition(0);
                        clip.start();
                    } catch (Exception e) {
                        e.printStackTrace(System.err);
                    }
                }
            };
            new Thread(soundPlayer).start();
        }
    }
}

您的片段引发了几个问题:

Swing GUI对象应仅在上构造和操作

给每个不同的声音提供自己的流和片段;只初始化每个剪辑一次,而不是每次播放该剪辑

AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(…);
Clip clip = AudioSystem.getClip( );
clip.open(audioInputStream);
尽管音响系统在单独的线程中播放剪辑,但您可能希望在单独的线程中定位和启动剪辑;这将最大限度地减少EDT上的延迟并增强活动性

另请参见标签和此相关信息

增编:SSCCE

import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.net.URL;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;

/**
 * @see https://stackoverflow.com/a/17130160/230513
 * @see http://pscode.org/media/
 * @see http://www.soundjay.com/beep-sounds-1.html
 */
public class Test {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Test().display();
            }
        });
    }

    private void display() {
        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLayout(new FlowLayout());
        f.add(new JButton(new SoundAction("Play 1",
            "http://pscode.org/media/leftright.wav")));
        f.add(new JButton(new SoundAction("Play 2",
            "http://www.soundjay.com/button/beep-1.wav")));
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    class SoundAction extends AbstractAction {

        private Clip clip;

        public SoundAction(String name, String location) {
            super(name);
            try {
                URL url = new URL(location);
                AudioInputStream ais = AudioSystem.getAudioInputStream(url);
                clip = AudioSystem.getClip();
                clip.open(ais);
            } catch (Exception e) {
                e.printStackTrace(System.err);
            }
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            // Runnable optional
            Runnable soundPlayer = new Runnable() {
                @Override
                public void run() {
                    try {
                        clip.setMicrosecondPosition(0);
                        clip.start();
                    } catch (Exception e) {
                        e.printStackTrace(System.err);
                    }
                }
            };
            new Thread(soundPlayer).start();
        }
    }
}

简单地看一下,您是否尝试过在使用audioInputStream后关闭它?也许字符的读取方式不正确。你试过用standerd e替换它们吗?音频也应该在它自己的线程中播放你的歌曲你应该在另一个线程中播放你的歌曲,因为如果你在gui EDT的同一线程中播放,它会被阻止。我总是觉得从音频系统中检索到的用于播放的东西在它自己的线程中运行,傻我。只是看一眼,您是否尝试过在使用audioInputStream后关闭它?可能字符的读取方式不正确。你试过用standerd e替换它们吗?音频也应该在它自己的线程中播放你的歌曲你应该在另一个线程中播放你的歌曲,因为如果你在与gui EDT相同的线程中播放,它会被阻止。我总是觉得从音频系统检索到的用于播放的内容在它自己的线程中运行,傻我。