单击btnSetTime时为什么没有声音播放?

时间:2017-11-14 22:22:28

标签: java swing awt javasound

我为自己制作闹钟,因为我喜欢制作自己的软件。我在构建Java GUI方面相对较新,但我在Python Tkinter GUI构建方面经验丰富。

当我使用它时,当它想要在时间等于实际时间时响铃时,它没有发出声音......我试图找到这个问题的答案,但没有任何东西响了这实际上会有所帮助。

以下是代码:

import javax.sound.sampled.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.io.File;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Objects;

public class AlarmClock extends JFrame {
    private AlarmClock() {
        Container cp = getContentPane();
        cp.setLayout(new FlowLayout());

        JLabel lblSetTime = new JLabel("Set Time to Ring:");
        cp.add(lblSetTime);
        JTextField txtSetTime = new JTextField("", 3);
        txtSetTime.setEditable(true);
        cp.add(txtSetTime);
        JButton btnSetTime = new JButton("Set Time");
        cp.add(btnSetTime);
        JLabel lblSuccessful = new JLabel();
        cp.add(lblSuccessful);
        //JLabel lblTimeLeft = new JLabel("Time to Alarm:");
        //cp.add(lblTimeLeft);
        //JTextField txtTimeLeft = new JTextField("", 3);
        //txtTimeLeft.setEditable(false);
        //cp.add(txtTimeLeft);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Alarm Clock");
        setSize(300, 100);
        setVisible(true);

        btnSetTime.addActionListener((ActionEvent actionEvent) -> {
            String time = txtSetTime.getText();
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            String loginTime = sdf.format(cal.getTime());

            File soundFile = new File("Alarm-Clock-Sound.wav");

            if (Objects.equals(time, loginTime)) {
                try {
                    URL url = this.getClass().getClassLoader().getResource("Alarm-Clock-Sound.wav");
                    AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
                    Clip clip = AudioSystem.getClip();
                    clip.open(audioIn);
                    clip.start();
                } catch (UnsupportedAudioFileException | LineUnavailableException | IOException e) {
                    e.printStackTrace();
                }
            }

            lblSuccessful.setText("Successful!");
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(AlarmClock::new);
    }
}

任何帮助都会很棒!!谢谢所有感兴趣的人! :)

0 个答案:

没有答案