'''Pg_midi_sound101.py Play midi music files (also mp3 files) using pygame Tested with Python273/331 and pygame192 by vegaseat ''' Import pygame as pg Def play_music (music_file ): ''' Stream music with mixer. music module in blocking manner This will 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 )) Failed t pygame. error: Print ("File {} not found! {} ". Format (music_file, pg. get_error ())) Return Pg. mixer. music. play () # Check if playback has finished While pg. mixer. music. get_busy (): Clock. tick (30) # Pick a midi or MP3 music file you have in the working folder # Or give full pathname Music_file = "Latin. mid" # Music_file = "drumtrack.pdf" Freq = 44100 # audio CD quality Bitsize =-16 # unsigned 16 bit Channels = 2 #1 is mono, 2 is stereo Buffer = 2048 # number of samples (experiment to get right sound) Pg. mixer. init (freq, bitsize, channels, buffer) # Optional volume 0 to 1.0 Pg. mixer. music. set_volume (0.8) Try: Play_music (music_file) Except t KeyboardInterrupt: # If user hits Ctrl/C then exit # (Works only in console mode) Pg. mixer. music. fadeout (1000) Pg. mixer. music. stop () Raise SystemExit |