其他分享
首页 > 其他分享> > 重构思维系列-如何写出好代码1

重构思维系列-如何写出好代码1

作者:互联网

package service.alarmClock;

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class AlarmClock {
    /**
     * 闹钟提醒-功能介绍:
     * 每当早上、中午、晚上时,分别有对应类型的播放音乐,分别对应不同的音量、不同的曲子、不同的播放时长
     * 1、如果是周末就不要响
     * 2、如果是早上7点,播放起床闹钟,    持续1小时,音量3
     * 3、如果是中午12点,播放中午休息闹钟,持续1分钟,音量80
     * 4、如果是晚上12点,播放睡觉催眠曲, 持续30分钟,音量15
     */
    public void run() throws IOException, UnsupportedAudioFileException, LineUnavailableException, InterruptedException {

        String soundFileSrc = ""; //定义闹钟铃声的声音文件地址
        int continueSeconds = 0; //闹钟持续的时间(单位是秒)
        int soundVolume = 0;    //闹钟的音量

        while (true) {
            // 每秒循环一次
            Thread.sleep(1000);

            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
            // 获取当前时分秒格式的时间
            String currentTime = formatter.format(calendar.getTime());

            // 周末不提醒,获取今天是星期几,西方周日是第1天,周六是第7天
            int week = calendar.get(Calendar.DAY_OF_WEEK);
            if (week == 1 || week == 7) {
                continue;
            }

            switch (currentTime) {
                case "07:00:00":
                    soundFileSrc = "./wake.mp3";
                    continueSeconds = 60 * 60;
                    soundVolume = 3; //微弱的音量
                    break;
                case "12:00:00":
                    soundFileSrc = "./rest.wav";
                    continueSeconds = 60;
                    soundVolume = 80;
                    break;
                case "00:00:00":
                    soundFileSrc = "./sleep.mp3";
                    continueSeconds = 60 * 30;
                    soundVolume = 15;
                    break;
            }
            System.out.println("当前时间是: " + currentTime);

            if (!soundFileSrc.equals("")) {
                AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundFileSrc));

                Clip clip = AudioSystem.getClip();

                clip.open(audioInputStream);

                FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.VOLUME);

                gainControl.setValue(soundVolume);

                clip.start();
                Thread.sleep(continueSeconds * 1000);
                soundFileSrc = "";
                clip.stop();
            }
        }
    }
}

标签:重构,00,soundFileSrc,clip,思维,写出,闹钟,soundVolume,import
来源: https://blog.csdn.net/weixin_38256311/article/details/123217834