Как сделать будильник на python

от admin

Блог питониста

Хочется написать себе будильник, который стартовал бы в определенное время, проигрывал бы несколько композиций и выключался бы до следующего раза. Это возможно сделать, используя, например, библиотеку gstreamer.

Я буду писать его под Ubuntu, поскольку использую данную ОС дома. Также можно попробовать сделать то же самое под Raspbian, если у вас есть Raspberry. Будильник будет работать как демон, тоесть не будет блокировать терминал, а будет работать в фоновом режиме.

Установка библиотек

Установить небходимые библиотеки на Debian — системах можно так:

apt-get install python-gst0.10 gstreamer0.10-plugins-good gstreamer0.10-plugins-ugly

Чтобы проверить, что все работает корректно, откройте интерпретатор python и сделайте такие импорты:

Также можно попробовать проиграть какой-нибудь аудиофайл:

gst-launch-0.10 filesrc location=/path/to/file/test.mp3 ! decodebin ! audioconvert ! autoaudiosink

Для демонизации процесса понадобится библиотека daemonize, установить ее можно так:

pip install daemonize

Пишем будильник

Простейший демон с помощью данной библиотеки:

Полезная команда, которая вам может пригодится, если вы запустили этот тестовый демон, или если вам нужно точно убить какой-то процесс в системе, сколько бы экземпляров данного процесса ни было:

Разберем по частям, следующая команда выведет список процессов:

Дальше отберем только python процессы:

Затем удалим из полученного списка саму нашу команду

И, наконец, отберем PID’ы процессов и убьем их:

Gstreamer — это библиотека основанная на плагинах, один такой плагин — playbin мы будем использовать. Данные в gstreamer проходят через pipeline. Нам придется использовать элемент playbin для построения pipeline. Также будет задействована библиоткека gobject. Простейший аудиоплеер с помощью gstreamer:

При конце каждой песни на шину приходит сообщение MESSAGE_EOS, пользуясь этим, можно переключать песни, что и реализовано на строках 50-53.

Alarm Clock with Python

An alarm clock is a clock with a function that can be activated to ring at a time set in advance, used to wake someone up. In this article, I’ll walk you through how to write a Python program to create an alarm clock with Python.

How to Create an Alarm Clock with Python?

As the title suggests, our task here is to write a python script that creates an alarm clock. For this task, I will be using the DateTime module in Python to create an alarm clock and the sound library in Python to play the alarm sound.

The DateTime module comes preinstalled in the Python programming language so you can easily import it in your program. The playsound library can be easily installed by using a pip command; pip install playsound. I hope you will be able to install it in your systems, now let’s see how to write a program to create an alarm with Python.

Alarm Clock with Python

Before writing the program you should know that you also need an alarm tone which will ring at the time of the alarm. So you can download an alarm tune from here. Now as we are ready with the libraries and the alarm song, let’s see how to write a program to create an alarm clock with Python:

The user input should be in a format of hours: minutes: and then seconds. You will start listening to the song as you will reach the time that has been set. To test your code set the time 2 or 3 minutes later from the time you are giving the user input.

Summary

This idea can be implemented in software applications also, so you now have an idea of what can be a good Python project other than just designing the User interface of an application.

Читать:
Asus core unlocker что это

I hope you liked this article on how to write a program to create an alarm with Python. Feel free to ask your valuable questions in the comments section below.

добрый будильник на python

Для запуска вам потребуется установить непосредственной сам язык Python , Python for Windows extensions и положить библиотеку Winamp.py в папку Lib, расположенную в установочной директории Python. Эту библиотеку написал Arkadiusz Wahlig.

Скрипт будильника расположен тут, и запускается следующим образом:
goodalarm.py

Tkinter Alarm Clock – A Step-By-Step Guide

Tkinter Alarm Clock

Hello there! Today in this tutorial, we will be developing a basic Python Tkinter Alarm Clock.

There is no wonder that an alarm clock is always useful to warn us while we sleep, take a brief nap, or to remind us about the job, we always get ignorant about.

Introduction to the Project

The project makes use of some python libraries namely, datetime and Tkinter.

The project makes use of the current date and time along with a feature to set an alarm according to the current date and time found.

Building the Tkinter Alarm Clock

Let’s not waste anymore time and start off building the project now!

1. Importing required modules

Before building any project, the first step is importing all the necessary libraries and modules that we require for the project.

Let’s know about each module we have just imported:

  1. Tkinter module: Helps us to create a window for the user to use the application
  2. datetime and time modules: Help us to handle dates and time and manipulate them when needed.
  3. winsound module: Helpful to generate sounds for our alarm clock.

2. Creating a function for the alarm

The next step involves creating functions for the alarm clock. Let’s look at the code for the same first.

The function named Alarm handles the main functionality of the application. The function takes the alarm time the user sets in the entry boxes of the window as an argument.

sleep function stops the execution of the program until it gets the time values entered by the user.

Then we get the current date and time using the datetime.now function and store the time and date into separate variables with the help of strftime function.

The the program checks when the current time matches the alarm time set by the user. When the condition is true then the sound is played using the winsound module or else the timer continues.

A new function is defined to get the input from the user entry boxes and pass it to the previous function.

3. Creating the Tkinter Window

The final step is to create the main window of the application with all the widgets and features defined. The code for the same is shown below.

Complete Code for Tkinter Alarm Clock

Sample Output

The video below displays the working of the application. You can customize the window and variables according to your preferences.

Conclusion

Congratulations! Today, we have successfully learned how to make an Alarm Clock using Tkinter module of Python. We also learned about extracting current date and time and playing sound at the particular instant of time.

Похожие статьи