This article describes how Python uses Pygame to play MIDI and MP3 files. Share to everyone for your reference. The implementation method is as follows:
"' Pg_midi_sound101.py play MIDI Music files (also mp3 files) using Pygame tested with python273/331 and pygame192 by ve
Gaseat ' Import Pygame as pg Def play_music (music_file): ' Stream music with Mixer.music module in blocking manner This would stream the sound from disk while playing ' clock = Pg.time.Clock () try:pg.mixer.music.load (music _file) Print ("Music file {} loaded!"). Format (music_file)) except Pygame.error:print ("file {} not found! {} '. Format (Music_file, Pg.get_error ()) return to Pg.mixer.music.play () # Check if playback has finished while PG.M Ixer.music.get_busy (): Clock.tick # Pick a midi or MP3 music file you have in the Working folder # or give full PA Thname music_file = "Latin.mid" #music_file = "Drumtrack.mp3" freq = 44100 # audio CD Quality bitsize = -16 # unsigned 1 6 bit channels = 2 # 1 is mono, 2 was stereo buffer = 2048 # Number of samples (experiment to get right sound) pg.mixer.i NIT (Freq, bitsize, channels, bufFER) # Optional Volume 0 to 1.0 pg.mixer.music.set_volume (0.8) Try:play_music (music_file) except Keyboardinterrupt: # If user hits ctrl/c then exit # (works only in console mode) pg.mixer.music.fadeout (1000) pg.mixer.music.stop () r Aise Systemexit
I hope this article will help you with your Python programming.