Programming music in python

Make your own music player in python

In this tutorial, you’re going to learn how to make your own MP3 Music Player in Python using pygame and Tkinter libraries which is able to load, play, pause, and stop the music.

Requirements

Installation

sudo apt-get install python3-tk pip3 install pygame 

Now once everything is ready Installed, we now ready to begin coding our very own music player

Let’s get started

We gonna use Tkinter to render our application menu and buttons, and also loading the music from files and then pygame library to play, pause and stop the music

Basics of pygame

Pygame has an inbuilt method called mixer () which provides us intuitive syntax on dealing with sounds files in python, we will see ;

  • loading and playing music
  • pausing and unpausing music
  • stoping the music file
Читайте также:  Html css background image height

loading and playing music with pygame

To play music with pygame you’re firstly supposed to import mixer(), initialize it through init(), *and then using *music.load() to load the music and finally playing it with music.play().

Example of usage

from pygame import mixer mixer.init() #Initialzing pyamge mixer mixer.music.load.('filename.mp3') #Loading Music File mixer.music.play() #Playing Music with Pygame 

Pausing and unpausing music with pygame.

use* music.pause() and music.unpause()* to pause and unpause your music, but make your music file is loaded first before using these methods.

mixer.music.pause() #pausing music file mixer.music.unpause() #unpausing music file 

Stop a music file

use music.stop() to stop your music completely from playing, once you use this method the loaded music will be cleared in pygame memory.

Building your music player exoskeleton

We have already covered the basics of playing music with python, now it’s time to begin designing our application user interface

First Let us import all necessary Library

from tkinter import * from tkinter import filedialog from pygame import mixer 

Let’s now implement our class & Buttons for our application

class MusicPlayer: def __init__(self, window ): window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0) Load = Button(window, text = 'Load', width = 10, font = ('Times', 10), command = self.load) Play = Button(window, text = 'Play', width = 10,font = ('Times', 10), command = self.play) Pause = Button(window,text = 'Pause', width = 10, font = ('Times', 10), command = self.pause) Stop = Button(window ,text = 'Stop', width = 10, font = ('Times', 10), command = self.stop) Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60) self.music_file = False self.playing_state = False 

Let’s now add the method to the class we just made to load music file from our computer, just as shown in the code below

Adding Load Method to our MusicPlayer class

class MusicPlayer: def __init__(self, window ): window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0) Load = Button(window, text = 'Load', width = 10, font = ('Times', 10), command = self.load) Play = Button(window, text = 'Play', width = 10,font = ('Times', 10), command = self.play) Pause = Button(window,text = 'Pause', width = 10, font = ('Times', 10), command = self.pause) Stop = Button(window ,text = 'Stop', width = 10, font = ('Times', 10), command = self.stop) Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60) self.music_file = False self.playing_state = False def load(self): self.music_file = filedialog.askopenfilename() 

After Loading the Music file from the file we need a function to Play our Music File, Let’s make it using the concepts we just learned above.

Adding Play Method to our class

class MusicPlayer: def __init__(self, window ): window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0) Load = Button(window, text = 'Load', width = 10, font = ('Times', 10), command = self.load) Play = Button(window, text = 'Play', width = 10,font = ('Times', 10), command = self.play) Pause = Button(window,text = 'Pause', width = 10, font = ('Times', 10), command = self.pause) Stop = Button(window ,text = 'Stop', width = 10, font = ('Times', 10), command = self.stop) Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60) self.music_file = False self.playing_state = False def load(self): self.music_file = filedialog.askopenfilename() def play(self): if self.music_file: mixer.init() mixer.music.load(self.music_file) mixer.music.play() 

After adding the Play Method to our class we need a Method to pause and unpause & also to Stop the Music

Finally Let’s add the pause and stop method to our class

class MusicPlayer: def __init__(self, window ): window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0) Load = Button(window, text = 'Load', width = 10, font = ('Times', 10), command = self.load) Play = Button(window, text = 'Play', width = 10,font = ('Times', 10), command = self.play) Pause = Button(window,text = 'Pause', width = 10, font = ('Times', 10), command = self.pause) Stop = Button(window ,text = 'Stop', width = 10, font = ('Times', 10), command = self.stop) Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60) self.music_file = False self.playing_state = False def load(self): self.music_file = filedialog.askopenfilename() def play(self): if self.music_file: mixer.init() mixer.music.load(self.music_file) mixer.music.play() def pause(self): if not self.playing_state: mixer.music.pause() self.playing_state=True else: mixer.music.unpause() self.playing_state = False def stop(self): mixer.music.stop() 

Let’s look at our Final will app (app.py)

from tkinter import * from tkinter import filedialog from pygame import mixer class MusicPlayer: def __init__(self, window ): window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0) Load = Button(window, text = 'Load', width = 10, font = ('Times', 10), command = self.load) Play = Button(window, text = 'Play', width = 10,font = ('Times', 10), command = self.play) Pause = Button(window,text = 'Pause', width = 10, font = ('Times', 10), command = self.pause) Stop = Button(window ,text = 'Stop', width = 10, font = ('Times', 10), command = self.stop) Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60) self.music_file = False self.playing_state = False def load(self): self.music_file = filedialog.askopenfilename() def play(self): if self.music_file: mixer.init() mixer.music.load(self.music_file) mixer.music.play() def pause(self): if not self.playing_state: mixer.music.pause() self.playing_state=True else: mixer.music.unpause() self.playing_state = False def stop(self): mixer.music.stop() root = Tk() app= MusicPlayer(root) root.mainloop() 

Output

If you run the above code the output will be as shown below, now you can play around with it by loading, playing, pausing, and stopping the music, full demo in youtube link at the end of the article.

View demo on youtube

Based on your interest I recommend you to also check these;

In case of any comment,suggestion or difficulties drop it on the comment box below, and then I will get back to you ASAP.

Kalebu / MusicPlayer

A music player application made with python for learning purpose

MusicPlayer

Simple Basic Player implemented in Python using Tkinter & Pygame Library

Источник

Пишем простой синтезатор на Python

В предыдущем посте я писал про генерацию звука на Rust`е для азбуки Морзе.

Сегодняшняя статья будет короткой, но в ней мы рассмотрим написание упрощенной версии программного синтезатора.

Ну что же, поехали!

Генерация звука

Не будем изобретать что-то новое, а возьмём функцию генерации звука из прошлой статьи и адаптируем её под python:

import numpy as np # частота дискретизации SAMPLE_RATE = 44100 # 16-ти битный звук (2 ** 16 -- максимальное значение для int16) S_16BIT = 2 ** 16 def generate_sample(freq, duration, volume): # амплитуда amplitude = np.round(S_16BIT * volume) # длительность генерируемого звука в сэмплах total_samples = np.round(SAMPLE_RATE * duration) # частоте дискретизации (пересчитанная) w = 2.0 * np.pi * freq / SAMPLE_RATE # массив сэмплов k = np.arange(0, total_samples) # массив значений функции (с округлением) return np.round(amplitude * np.sin(k * w)) 

Теперь, когда у нас есть функция генерации звука любой частоты, длительности и громкости, остаётся сгененрировать ноты из первой октавы и подать их на устройство воспроизведения.

Генерация звука нот

Запишем частоты нот первой октавы в массив и напишем функцию, которая будет их генерировать

# до ре ми фа соль ля си freq_array = np.array([261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88]) def generate_tones(duration): tones = [] for freq in freq_array: # np.array нужен для преобразования данных под формат 16 бит (dtype=np.int16) tone = np.array(generate_sample(freq, duration, 1.0), dtype=np.int16) tones.append(tone) return tones 

Остаётся последнее — вывести звук.

Вывод звука

Для вывода звука будем использовать кроссплатформенную библиотеку PyAudio.

Так же нам понадобится как-то отслеживать нажатия клавиш, чтобы наша программа была похожа на настоящий синтезатор. Поэтому я взял pygame, т.к. он прост в работе. Вы же можете использовать то, что вам больше нравится!

import pyaudio as pa import pygame # . место для предыдущего кода . # наши клавиши key_names = ['a', 's', 'd', 'f', 'g', 'h', 'j'] # коды клавиш key_list = list(map(lambda x: ord(x), key_names)) # состояние клавиш (нажато/не нажато) key_dict = dict([(key, False) for key in key_list]) if __name__ == '__main__': # длительность звука duration_tone = 1/64.0 # генерируем тона с заданной длительностью tones = generate_tones(duration_tone) # инициализируем p = pa.PyAudio() # создаём поток для вывода stream = p.open(format=p.get_format_from_width(width=2), channels=2, rate=SAMPLE_RATE, output=True) # размер окна pygame window_size = 320, 240 # настраиваем экран screen = pygame.display.set_mode(window_size) pygame.display.flip() running = True while running: # обрабатываем события for event in pygame.event.get(): # событие закрытия окна if event.type == pygame.QUIT: running = False # нажатия клавиш if event.type == pygame.KEYDOWN: if event.key == ord('q'): running = False # обрабатываем нажатые клавиши по списку key_list for (index, key) in enumerate(key_list): if event.key == key: # зажимаем клавишу key_dict[key] = True # отпускание клавиш if event.type == pygame.KEYUP: for (index, key) in enumerate(key_list): if event.key == key: # отпускаем клавишу key_dict[key] = False # обрабатываем нажатые клавиши for (index, key) in enumerate(key_list): # если клавиша нажата if key_dict[key] == True: # то выводим звук на устройство stream.write(tones[index]) # закрываем окно pygame.quit() # останавливаем устройство stream.stop_stream() # завершаем работу PyAudio stream.close() p.terminate() 

Вот и всё. Наш минимальный синтезатор готов!

Полезные ссылки

Источник

Оцените статью