Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/C5 - Sequence Models/Week 1/Jazz improvisation with LSTM/midi.py
Views: 4819
"""1File: midi.py2Author: Addy7713Description:4A script which converts MIDI files to WAV and optionally to MP3 using ffmpeg.5Works by playing each file and using the stereo mix device to record at the same time6"""789import pyaudio # audio recording10import wave # file saving11import pygame # midi playback12import fnmatch # name matching13import os # file listing141516#### CONFIGURATION ####1718do_ffmpeg_convert = True # Uses FFmpeg to convert WAV files to MP3. Requires ffmpeg.exe in the script folder or PATH19do_wav_cleanup = True # Deletes WAV files after conversion to MP320sample_rate = 44100 # Sample rate used for WAV/MP321channels = 2 # Audio channels (1 = mono, 2 = stereo)22buffer = 1024 # Audio buffer size23mp3_bitrate = 128 # Bitrate to save MP3 with in kbps (CBR)24input_device = 1 # Which recording device to use. On my system Stereo Mix = 125262728# Begins playback of a MIDI file29def play_music(music_file):3031try:32pygame.mixer.music.load(music_file)3334except pygame.error:35print ("Couldn't play %s! (%s)" % (music_file, pygame.get_error()))36return3738pygame.mixer.music.play()39404142# Init pygame playback43bitsize = -16 # unsigned 16 bit44pygame.mixer.init(sample_rate, bitsize, channels, buffer)4546# optional volume 0 to 1.047pygame.mixer.music.set_volume(1.0)4849# Init pyAudio50format = pyaudio.paInt1651audio = pyaudio.PyAudio()52535455try:5657# Make a list of .mid files in the current directory and all subdirectories58matches = []59for root, dirnames, filenames in os.walk("./"):60for filename in fnmatch.filter(filenames, '*.mid'):61matches.append(os.path.join(root, filename))6263# Play each song in the list64for song in matches:6566# Create a filename with a .wav extension67file_name = os.path.splitext(os.path.basename(song))[0]68new_file = file_name + '.wav'6970# Open the stream and start recording71stream = audio.open(format=format, channels=channels, rate=sample_rate, input=True, input_device_index=input_device, frames_per_buffer=buffer)7273# Playback the song74print("Playing " + file_name + ".mid\n")75play_music(song)7677frames = []7879# Record frames while the song is playing80while pygame.mixer.music.get_busy():81frames.append(stream.read(buffer))8283# Stop recording84stream.stop_stream()85stream.close()868788# Configure wave file settings89wave_file = wave.open(new_file, 'wb')90wave_file.setnchannels(channels)91wave_file.setsampwidth(audio.get_sample_size(format))92wave_file.setframerate(sample_rate)9394print("Saving " + new_file)9596# Write the frames to the wave file97wave_file.writeframes(b''.join(frames))98wave_file.close()99100# Call FFmpeg to handle the MP3 conversion if desired101if do_ffmpeg_convert:102os.system('ffmpeg -i ' + new_file + ' -y -f mp3 -ab ' + str(mp3_bitrate) + 'k -ac ' + str(channels) + ' -ar ' + str(sample_rate) + ' -vn ' + file_name + '.mp3')103104# Delete the WAV file if desired105if do_wav_cleanup:106os.remove(new_file)107108# End PyAudio109audio.terminate()110111except KeyboardInterrupt:112# if user hits Ctrl/C then exit113# (works only in console mode)114pygame.mixer.music.fadeout(1000)115pygame.mixer.music.stop()116raise SystemExit117118