Skip to content

[Python] How to play music

Last Updated on 2021-03-14 by Clay


Introduction

If you search about "How to do a simple Python side project", you will find the online tutorial is teaching "how to make a music player by yourself". In any case, being able to customize a music player by yourself is quite interesting to think about.

However, I have tried to encounter many methods of playing music in Python tutorial article that could not be executed.

So, I recorded the method that I tested successfully.

I think there are two ways to play music in Python:

  • Use os module to call the os default player to play
  • Use PyGame package

Many people also recommend the mp3play module, but I looked at the underlying code, and it seems to be Python2, which is not easy to run on my side. If you are accustomed to writing programs in Python2, you may be able to refer to it more or less.

Among them, I prefer PyGame's method (in background execution), because I just wanted to make a music player at that time. Below, I will record how to play music in Python.


Play with default player

This program is very simple and very simple. Suppose we have an MP3 file, called "test.mp3" first.

import os
os.system('test.mp3')


Output:

Since I was testing on a Windows operating system, I jumped out of the default player.


PyGame

PyGame is a Python package dedicated to writing games. Although many people comment that it is not suitable for real game development, if you ignore its performance and art (art is super difficult!), in fact, its syntax is written in Python. So the development speed can be regarded as very fast.

If you are interested in PyGame, please refer to their official website: https://www.pygame.org/news

There are even introductions to many games completed with PyGame. It is good to see how far PyGame can do it.

Okay, let’s return to the topic of how to use PyGame for music playback.

If you use it for the first time, you need to download it with the following command.

pip3 install pygame

After downloading, I started to talk about the second pitfall I encountered: PyGame music playback modules are played in a "flow" way, and some teachings found on the Internet cannot run at least for me. of.

The following simple example:

import pygame


pygame.mixer.init()
pygame.mixer.music.set_volume(1.0)

while True:
    if not pygame.mixer.music.get_busy():
        pygame.mixer.music.load('test.mp3')
        pygame.mixer.music.play()


The volume of set_volume is the interval [0.0-1.0].

In this way, you should be able to play music smoothly. If you are lucky enough to go back and continue to strengthen the music player, maybe you can write more carefully and post another article.

Tags:

Leave a ReplyCancel reply

Exit mobile version