Как в питоне добавить музыку

pygame-ce documentation
The music module is closely tied to pygame.mixer pygame module for loading and playing sounds . Use the music module to control the playback of music in the sound mixer.
The difference between the music playback and regular Sound playback is that the music is streamed, and never actually loaded all at once. The mixer system only supports a single music stream at once.
On older pygame versions, MP3 support was limited under Mac and Linux. This changed in pygame v2.0.2 which got improved MP3 support. Consider using OGG file format for music as that can give slightly better compression than MP3 in most cases.
This will load a music filename/file object and prepare it for playback. If a music stream is already playing it will be stopped. This does not start the music playing.
If you are loading from a file object, the namehint parameter can be used to specify the type of music data in the object. For example: load(fileobj, "ogg") .
Changed in pygame 2.0.2: Added optional namehint argument
Changed in pygame-ce 2.2.0: Raises FileNotFoundError instead of pygame.error standard pygame exception if file cannot be found
This closes resources like files for any music that may be loaded.
New in pygame 2.0.0.
This will play the loaded music stream. If the music is already playing it will be restarted.
loops is an optional integer argument, which is 0 by default, which indicates how many times to repeat the music. The music repeats indefinitely if this argument is set to -1 .
start is an optional float argument, which is 0.0 by default, which denotes the position in time from which the music starts playing. The starting position depends on the format of the music played. MP3 and OGG use the position as time in seconds. For MP3 files the start time position selected may not be accurate as things like variable bit rate encoding and ID3 tags can throw off the timing calculations. For MOD music it is the pattern order number. Passing a start position will raise a NotImplementedError if the start position cannot be set.
fade_ms is an optional integer argument, which is 0 by default, which denotes the period of time (in milliseconds) over which the music will fade up from volume level 0.0 to full volume (or the volume level previously set by set_volume() ). The sample may end before the fade-in is complete. If the music is already streaming fade_ms is ignored.
Changed in pygame 2.0.0: Added optional fade_ms argument
Resets playback of the current music to the beginning. If pause() has previously been used to pause the music, the music will remain paused.
rewind() supports a limited number of file types and notably WAV files are NOT supported. For unsupported file types use play() which will restart the music that’s already playing (note that this will start the music playing again even if previously paused).
Stops the music playback if it is currently playing. endevent will be triggered, if set. It won’t unload the music.
Temporarily stop playback of the music stream. It can be resumed with the unpause() function.
This will resume the playback of a music stream after it has been paused.
Fade out and stop the currently playing music.
The time argument denotes the integer milliseconds for which the fading effect is generated.
Note, that this function blocks until the music has faded out. Calls to fadeout() and set_volume() will have no effect during this time. If an event was set using set_endevent() it will be called after the music has faded.
Set the volume of the music playback.
The volume argument is a float between 0.0 and 1.0 that sets the volume level. When new music is loaded the volume is reset to full volume. If volume is a negative value it will be ignored and the volume will remain set at the current level. If the volume argument is greater than 1.0 , the volume will be set to 1.0 .
Returns the current volume for the mixer. The value will be between 0.0 and 1.0 .
Returns True when the music stream is actively playing. When the music is idle this returns False. In pygame 2.0.1 and above this function returns False when the music is paused. In pygame 1 it returns True when the music is paused.
Changed in pygame 2.0.1: Returns False when music paused.
This sets the position in the music file where playback will start. The meaning of "pos", a float (or a number that can be converted to a float), depends on the music format.
For MOD files, pos is the integer pattern number in the module. For OGG it is the absolute position, in seconds, from the beginning of the sound. For MP3 files, it is the relative position, in seconds, from the current position. For absolute positioning in an MP3 file, first call rewind() .
Other file formats are unsupported. Newer versions of SDL_mixer have better positioning support than earlier ones. A pygame.error standard pygame exception is raised if a particular format does not support positioning.
Function set_pos() calls underlying SDL_mixer function Mix_SetMusicPosition .
New in pygame 1.9.2.
This gets the number of milliseconds that the music has been playing for. The returned time only represents how long the music has been playing; it does not take into account any starting position offsets.
This will load a sound file and queue it. A queued sound file will begin as soon as the current sound naturally ends. Only one sound can be queued at a time. Queuing a new sound while another sound is queued will result in the new sound becoming the queued sound. Also, if the current sound is ever stopped or changed, the queued sound will be lost.
If you are loading from a file object, the namehint parameter can be used to specify the type of music data in the object. For example: queue(fileobj, "ogg") .
The following example will play music by Bach six times, then play music by Mozart once:
Changed in pygame 2.0.2: Added optional namehint argument
Changed in pygame-ce 2.2.0: Raises FileNotFoundError instead of pygame.error standard pygame exception if file cannot be found
This causes pygame to signal (by means of the event queue) when the music is done playing. The argument determines the type of event that will be queued.
The event will be queued every time the music finishes, not just the first time. To stop the event from being queued, call this method with no argument.
Returns the event type to be sent every time the music finishes playback. If there is no endevent the function returns pygame.NOEVENT .
If no arguments are passed returns a dictionary containing metadata of the currently loaded music stream, raises an exception if a music stream is not loaded. Available keys are "title" , "album" , "artist" , "copyright" . Values are strings containing corresponding retrieved metadata. If particular metadata was not found the value is an empty string. Here is an example:
How can I play an mp3 with pygame?
This outputs, «Process finished with exit code 0», but it doesn’t play anything. How can I resolve this problem?
![]()
7 Answers 7
The play function starts the music playing, but returns immediately. Then your program reaches it’s end, and the pygame object is automatically destroyed which causes the music to stop.
As you commented, it does play the music if you wait for it before exiting — because then the pygame object isn’t destroyed until the while loop finishes.
The music stops because it’s an asyncronous event, which means it’ll keep going with the script. then, the script stops instantly, not giving the music a chance to start. as stated before, you could use
however, even better is pygame.event.wait() , as it’ll wait for all asynchronous events to end.
![]()
Here is a super easy way.
![]()
I’ve found a good solution from thepythongamebook.com:
![]()
PyGame has 2 different modules for playing sound and music, the pygame.mixer module and the pygame.mixer.music module. This module contains classes for loading Sound objects and controlling playback. The difference is explained in the documentation:
The difference between the music playback and regular Sound playback is that the music is streamed, and never actually loaded all at once. The mixer system only supports a single music stream at once.
If you want to play a mp3 file, you need to initialize the module. Load the file with pygame.mixer.music.load . Invoke pygame.mixer.music.play() to start playback of the music stream. Finally, you have to wait for the file to play.
Use pygame.mixer.music.get_busy() to test if a sound is being mixed. Query the status of the mixer continuously in a loop.
In the loop, you need to delay the time by either pygame.time.delay or pygame.time.Clock.tick . In addition, you need to handle the events in the application loop. See pygame.event.get() respectively pygame.event.pump() :
For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.
Play sound in Python
Play sound on Python is easy. There are several modules that can play a sound file (.wav).
These solutions are cross platform (Windows, Mac, Linux).
The main difference is in the ease of use and supported file formats. All of them should work with Python 3. The audio file should be in the same directory as your python program, unless you specify a path.
Let’s explore the options!
Play sound in Python
playsound module
The playsound module is a cross platform module that can play audio files. This doesn’t have any dependencies, simply install with pip in your virtualenv and run!
Implementation is different on platforms. It uses windll.winm on Windows, AppKit.NSSound on Apple OS X and GStreamer on Linux.
I’ve tested this with Python 3.5.3. This should work with both WAV and MP3 files.
pydub
You can play sound files with the pydub module. It’s available in the pypi repository (install with pip).
This module can use PyAudio and ffmpeg underneath.
snack sound kit
The module snack sound kit can play several audio files: WAV, AU, AIFF, MP3, CSL, SD, SMP, and NIST/Sphere.
You can install it with your package manager: ‘apt install python3-tksnack’. For old versions there’s ‘python-tksnack’.
This module depends on Tkinter. That means that to play sound with this module, you’d also have to import the gui module Tkinter. The module doesn’t seem to have been updated in a while.
native player
You can also play sounds natively on your system. This requires you to have some kind of audio player installed on the terminal. On Linux you can use mpg123 for that.
Pygame Mixer – Sound and music
report this ad
report this ad
report this ad
This article covers the Pygame Mixer for audio and music.
No matter how great a game’s visuals and gameplay are, it’s not complete without a great soundtrack and music. Sound and Music are an important part of Video game immersion, and the experience is just lacking and empty without them.
The Python Pygame Mixer Library brings in support Audio and Sound playback. The great thing about it is that it’s not just restricted to making games. You can use the Mixer library all on it’s own as a stand alone library to play sound and music in your average Python program.
The sound effects used in this article have been acquired from the site, Freesound. You can find thousands of different sound effects for your program from this site, free of of charge or copyright issues. If you want to know more about the license under which these are available, follow this link.
Using the Mixer
First thing to know is that there is a difference between Music and Sound in the Pygame Mixer. Make sure to not confuse the two. Sound is mostly related to small side effects such as crash noises or beeps, generally anything just a few seconds long.
Music, on the other hand refers to longer tracks of audio, like background music or songs which can be up-to an hour long. It’s important to know this difference since there are separate libraries for Music and Sound.
Next, you should know about the types of files we’ll be using. The pygame mixer has the best support for wav files. It does support mp3 , but not very reliably, so it’s best to stick to wav files for maximum compatibility.
Pygame Mixer – Music
We’ll cover music first as it’s the larger and more complex library.
First thing to do is load up the appropriate music file into the music.load() function. Remember to keep both in the same directory else you’ll have to mention the full file path.
Music.play()
Now comes the music.play() function, which is used to play the audio clip that has been loaded up. This function can be called in a variety of manners to change how it plays the audio clip.
Calling the music.play() with no parameters or 0 passed into it will only play the audio clip once. Passing -1 as the parameter will play the audio clip indefinitely.
Passing any other positive integer besides 0 will result in the song being repeated that many times. For instance, passing 5 will repeat the song 5 times. So the song played once, and repeated 5 times, playing a total of 6 times.
Music.queue()
The Music library only allows one music file to be loaded and played at any given time. However, you are allowed to “queue” audio clips using the music.queue() function. Audio that has been queued will play right after the current music playing ends.
Music.stop()
All things must come to end, and so too must music. The music.stop() function is used like the “stop” button on an audio player. Do not confuse this with pause. The stop function will end your current music playback and if you call the play() function again, it will start from the beginning.
Music.pause() and Music.unpause()
Now obviously, you don’t always want to be using music.stop() . Sometimes you just want to pause so that you can pick up things later as you left them. Calling the music.pause() function will pause the music as it is.
Calling the unpause() function will resume the music.
Music.set_endevent()
Another interesting function in the pygame.mixer.music() library is the set_endevent() function. This function takes a number as a parameter and triggers the corresponding event once the music has stopped playing.
Calling pygame.USEREVENT and adding 1 ensures that the value of our user defined event is unique.
- pygame.mixer.music.rewind() – Rewinds the currently playing music to the start.
- pygame.mixer.music.set_volume () – Takes values in between 0.0 and 1.0. When a new music piece is loaded, these settings reset.
- pygame.mixer.music.get_busy () – Checks to see if music is currently playing or not. Returns False if not playing and True if it is.
Pygame Mixer – Sound
Using simple sound files in Pygame is much simpler than playing music.
There are two steps involved in playing a sound. First you must create a sound object, as shown below.
Next we call it with a simple play() method. An alternate option is to use the Sound.play() function, but that’s longer.
Unlike music, we can have multiple sound objects at any one point, though don’t try to play more than one at a time.
Example
To top it all off, we’ll show you a short demonstration of all the concepts discussed above. We’ve created a mini program using the GUI software Tkinter with buttons to control the music and sound. You won’t normally be using Tkinter with Pygame, but this is a good demonstration anyway. Especially if you’re looking to use only the Pygame mixer.
We’ve shown this demonstration in a video, and we’ve also included the source code here for you to practice with.
Other Audio Libraries
-
: Created with the purpose of being a simple one line function library. However, it has no functionality beyond audio playback of wav and mp3 files.: Another library used for cross platform and dependency free audio playback .
If you want to learn more about Pygame as a game development library, I recommend you our tutorial series on Pygame.
This marks the end of the Python Pygame Mixer article. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article can be asked in the comments section below.