Python makes a multifunctional music player

1. The idea of ​​making a player

Ideas for making a multifunctional music player

  1. Determine the player's needs and capabilities, such as which audio formats are supported, playlist management, looping, pausing, progress bar display, and more.

  2. Choose an appropriate Python GUI library, such as Tkinter, PyQt, etc. These libraries can help us realize various functions of the player in the graphical interface.

  3. Create controls such as player windows, menus, buttons, lists, etc., and arrange and arrange them.

  4. Write the logic code of the player, such as the realization of functions such as reading audio files, playing, pausing, stopping, switching songs, and looping.

  5. Through the event binding of the GUI library, the event of the control is associated with the logic code, so that the user can use various functions of the player by clicking the control.

  6. Test various functions of the player, and make corrections and optimizations.

2. Make player knowledge points and required modules

Making a multifunctional music player requires the following knowledge points and modules:

  1. GUI programming: Use Python GUI libraries such as Tkinter, PyQt, wxPython, etc. to create graphical user interfaces.

  2. Audio playback: Use Python audio libraries such as Pygame, PyAudio, pydub, etc. to play audio files.

  3. File operation: Use Python's os, glob and other modules to read, delete, search and other operations on audio files.

  4. Thread programming: use Python's threading module to implement multi-threading, so that audio playback and GUI operations can be performed simultaneously.

  5. Data structure: Use data structures such as Python lists to manage information such as music lists and playback history.

  6. Network programming: Use Python's socket, Requests and other modules to realize online music playback, lyrics download and other functions.

The Python modules that can be used to implement the above functions are:

Tkinter、Pygame、PyAudio、pydub、os、glob、threading、socket、Requests等。

3. The code display of the player

The following is the logic code of the Python multifunctional music player:

import pygame
import os

pygame.init()

class MusicPlayer:
    def __init__(self):
        self.playing = False
        self.paused = False
        self.volume = 0.5
        self.playing_index = None
        self.playlist = []

    def load_playlist(self, folder_path):
        self.playlist = []
        for filename in os.listdir(folder_path):
            if filename.endswith('.mp3'):
                self.playlist.append(os.path.join(folder_path, filename))

    def play(self, index):
        if self.playing_index == index:
            return
        if self.playing:
            pygame.mixer.music.stop()
            self.playing = False
        self.playing_index = index
        pygame.mixer.music.load(self.playlist[self.playing_index])
        pygame.mixer.music.set_volume(self.volume)
        pygame.mixer.music.play()
        self.playing = True
        self.paused = False

    def pause(self):
        if not self.playing:
            return
        if self.paused:
            pygame.mixer.music.unpause()
            self.paused = False
        else:
            pygame.mixer.music.pause()
            self.paused = True

    def stop(self):
        if not self.playing:
            return
        pygame.mixer.music.stop()
        self.playing = False
        self.paused = False

    def set_volume(self, volume):
        self.volume = volume
        if self.playing:
            pygame.mixer.music.set_volume(self.volume)

    def next(self):
        if not self.playing:
            return
        self.playing_index = (self.playing_index + 1) % len(self.playlist)
        self.play(self.playing_index)

    def prev(self):
        if not self.playing:
            return
        self.playing_index = (self.playing_index - 1) % len(self.playlist)
        self.play(self.playing_index)

    def loop(self):
        if not self.playing:
            return
        pygame.mixer.music.queue(self.playlist[self.playing_index])

music_player = MusicPlayer()
music_player.load_playlist('music_folder_path')

def mainloop():
    while True:
        # 读取键盘事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    music_player.pause()
                elif event.key == pygame.K_s:
                    music_player.stop()
                elif event.key == pygame.K_RIGHT:
                    music_player.next()
                elif event.key == pygame.K_LEFT:
                    music_player.prev()
                elif event.key == pygame.K_l:
                    music_player.loop()

        # 设置音量
        volume = pygame.key.get_pressed()[pygame.K_UP] - pygame.key.get_pressed()[pygame.K_DOWN]
        if volume != 0:
            new_volume = music_player.volume + volume * 0.05
            new_volume = min(max(new_volume, 0), 1)
            music_player.set_volume(new_volume)

        # 显示当前播放状态
        if music_player.playing:
            print('Now playing:', music_player.playlist[music_player.playing_index])
            print('Volume:', music_player.volume)
            print('Playing:', music_player.playing)
            print('Paused:', music_player.paused)

        pygame.time.wait(100)

if __name__ == '__main__':
    mainloop()

In the above code, MusicPlayerthe class encapsulates the logical functions of the music player. load_playlist()The method is used to read the audio file directory and store the audio file path in the playlist. play()The method is used to start playing a certain song, and pause()the method is used to pause/resume playback. , stop()the method is used to stop playback, set_volume()the method is used to set the volume, next()and prev()the method is used to switch songs, loop()which method is used to loop playback.

In mainloop()the method , use pygame.event.get()the method to read keyboard events, and call the method of MusicPlayerthe class . Use pygame.key.get_pressed()the method to read the volume adjustment keyboard event, and call set_volume()the method to set the volume according to the key press. Finally, use pygame.time.wait()the method to sleep the program for 100ms to avoid high CPU usage.

This code can be used as a basic template, which can be expanded according to your own needs, such as adding a display interface.

Guess you like

Origin blog.csdn.net/maomaodaren1/article/details/129544143