dari script ini improve file midi yang didapatkan agar lebih sempurna, tidak hanya 1 1…
- User
dari script ini improve file midi yang didapatkan agar lebih sempurna, tidak hanya 1 1 note saja, agar lebih sesuai dengan mp yang di convert , buatkan dengan lengkap dan tepat : import os import subprocess import shutil import tempfile from basic_pitch import ICASSP_2022_MODEL_PATH from basic_pitch.inference import predict_and_save
def download_song_from_spotify(song_query): """Download song from Spotify using spotdl.""" tmpdirname = tempfile.mkdtemp() try: print("Downloading song...") # Download the song with spotdl and save it in the temporary directory subprocess.run([ 'spotdl', 'download', song_query, '--output', os.path.join(tmpdirname, '{artist} - {title}.{output-ext}') ], check=True)
# Fetch the downloaded song downloaded_files = os.listdir(tmpdirname) if downloaded_files: song_file = os.path.join(tmpdirname, downloaded_files[0]) return song_file, downloaded_files[0], tmpdirname # Return song path, song file name, and temp directory else: print("Failed to download song.") return None, None, tmpdirname except subprocess.CalledProcessError as e: print(f"An error occurred while downloading the song: {e}") return None, None, tmpdirnamedef audio_to_midi_with_basic_pitch(audio_file, output_dir, song_name): """Convert audio file to MIDI using Basic Pitch.""" if not os.path.exists(audio_file): print(f"Error: Audio file {audio_file} not found.") return
try: # Run inference and save MIDI file predict_and_save( [audio_file], # List of audio files output_directory=output_dir, # Where to save outputs save_midi=True, # Save the MIDI file sonify_midi=False, # Disable sonification save_model_outputs=False, # Skip saving model outputs save_notes=False, # Skip saving detected notes model_or_model_path=ICASSP_2022_MODEL_PATH # The model used for inference ) # The actual MIDI file created will have the format: original_file_name_basic_pitch.mid base_name = os.path.splitext(os.path.basename(audio_file))[0] # Extract the base name of the audio file midi_file = os.path.join(output_dir, f"{base_name}_basic_pitch.mid") # Remove any file extension (e.g., .mp3) from the song name before renaming clean_song_name = os.path.splitext(song_name)[0] # Strip the .mp3 extension new_midi_file = os.path.join(output_dir, f"{clean_song_name}.mid") os.rename(midi_file, new_midi_file) # Delete the original mp3 file after conversion if os.path.exists(audio_file): os.remove(audio_file) print(f"Deleted the original audio file: {audio_file}") print(f"Conversion complete. MIDI file saved as {new_midi_file}.") except Exception as e: print(f"An error occurred during audio to MIDI conversion: {e}")---- Main Program ----
if name == "main": song_query = input("Enter the song title or Spotify link: ")
# Step 1: Download the song downloaded_song, song_name, tmpdirname = download_song_from_spotify(song_query) if downloaded_song: # Step 2: Convert audio to MIDI current_dir = os.path.dirname(os.path.abspath(__file__)) output_dir = os.path.join(current_dir, 'songs') if not os.path.exists(output_dir): os.makedirs(output_dir) # Create the 'songs' directory if it doesn't exist print("Converting audio to MIDI...") audio_to_midi_with_basic_pitch(downloaded_song, output_dir, song_name) # Clean up: Remove the temporary directory containing the downloaded song if os.path.exists(tmpdirname): shutil.rmtree(tmpdirname) else: print("Failed to download the song.") - Assistant
Halo! Saya memahami bahwa Anda ingin meningkatkan hasil konversi file MIDI agar lebih sempurna dan sesuai dengan file MP3 yang dikonversi, bukan hanya berupa not-not individual saja. Berikut adalah skrip yang telah ditingkatkan untuk menghasilkan file MIDI yang lebih akurat dan lengkap:
import os import subprocess import shutil import tempfile import librosa import soundfile as sf from basic_pitch import ICASSP_2022_MODEL_PATH from basic_pitch.inference import predict_and_save def download_song_from_spotify(song_query): """Download song from Spotify using spotdl.""" tmpdirname = tempfile.mkdtemp() try: print("Mengunduh lagu...") # Download the song with spotdl and save it in the temporary directory subprocess.run([ 'spotdl', 'download', song_query, '--output', os.path.join(tmpdirname, '{artist} - {title}.{output-ext}') ], check=True) # Fetch the downloaded song downloaded_files = os.listdir(tmpdirname) if downloaded_files: song_file = os.path.join(tmpdirname, downloaded_files[0]) return song_file, downloaded_files[0], tmpdirname # Return song path, song file name, and temp directory else: print("Gagal mengunduh lagu.") return None, None, tmpdirname except subprocess.CalledProcessError as e: print(f"Terjadi kesalahan saat mengunduh lagu: {e}") return None, None, tmpdirname def preprocess_audio(input_audio, output_audio, target_sr=22050): """Preprocess the audio file for better MIDI conversion.""" print("Melakukan pra-pemrosesan audio...") y, sr = librosa.load(input_audio, sr=None, mono=True) # Normalisasi y = librosa.util.normalize(y) # Resample jika diperlukan if sr != target_sr: y = librosa.resample(y, orig_sr=sr, target_sr=target_sr) sr = target_sr # Simpan file audio yang telah diproses sf.write(output_audio, y, sr) print(f"Audio pra-pemrosesan disimpan di {output_audio}.") def audio_to_midi_with_basic_pitch(audio_file, output_dir, song_name): """Convert audio file to MIDI using Basic Pitch.""" if not os.path.exists(audio_file): print(f"Error: Audio file {audio_file} tidak ditemukan.") return # Pra-pemrosesan audio preprocessed_audio = os.path.join(output_dir, 'preprocessed_' + os.path.basename(audio_file)) preprocess_audio(audio_file, preprocessed_audio) try: # Run inference and save MIDI file with custom parameters print("Mengonversi audio ke MIDI...") predict_and_save( [preprocessed_audio], # List of audio files output_directory=output_dir, # Where to save outputs save_midi=True, # Save the MIDI file sonify_midi=False, # Disable sonification save_model_outputs=False, # Skip saving model outputs save_notes=False, # Skip saving detected notes model_or_model_path=ICASSP_2022_MODEL_PATH, # The model used for inference onset_threshold=0.5, # Adjust thresholds as needed frame_threshold=0.3, minimum_note_length=30, # Minimum note length in ms minimum_frequency=50, # Minimum frequency in Hz maximum_frequency=8000 # Maximum frequency in Hz ) # The actual MIDI file created will have the format: original_file_name_basic_pitch.mid base_name = os.path.splitext(os.path.basename(preprocessed_audio))[0] # Extract the base name of the audio file midi_file = os.path.join(output_dir, f"{base_name}_basic_pitch.mid") # Remove any file extension (e.g., .mp3) from the song name before renaming clean_song_name = os.path.splitext(song_name)[0] # Strip the .mp3 extension new_midi_file = os.path.join(output_dir, f"{clean_song_name}.mid") os.rename(midi_file, new_midi_file) # Delete the original and preprocessed audio files after conversion if os.path.exists(audio_file): os.remove(audio_file) print(f"Menghapus file audio asli: {audio_file}") if os.path.exists(preprocessed_audio): os.remove(preprocessed_audio) print(f"Menghapus file audio pra-pemrosesan: {preprocessed_audio}") print(f"Konversi selesai. File MIDI disimpan sebagai {new_midi_file}.") except Exception as e: print(f"Terjadi kesalahan selama konversi audio ke MIDI: {e}") # ---- Main Program ---- if __name__ == "__main__": song_query = input("Masukkan judul lagu atau link Spotify: ") # Step 1: Download the song downloaded_song, song_name, tmpdirname = download_song_from_spotify(song_query) if downloaded_song: # Step 2: Convert audio to MIDI current_dir = os.path.dirname(os.path.abspath(__file__)) output_dir = os.path.join(current_dir, 'songs') if not os.path.exists(output_dir): os.makedirs(output_dir) # Create the 'songs' directory if it doesn't exist audio_to_midi_with_basic_pitch(downloaded_song, output_dir, song_name) # Clean up: Remove the temporary directory containing the downloaded song if os.path.exists(tmpdirname): shutil.rmtree(tmpdirname) else: print("Gagal mengunduh lagu.")Penjelasan Peningkatan Skrip:
-
Pra-pemrosesan Audio:
- Fungsi
preprocess_audio: Ditambahkan untuk melakukan pra-pemrosesan pada file audio sebelum konversi. Menggunakan pustakalibrosauntuk memuat audio, mengonversi ke mono, melakukan normalisasi, dan resampling jika diperlukan. - Normalisasi & Mono: Mengonversi audio ke mono dan normalisasi membantu model dalam menganalisis sinyal dengan lebih baik, mengurangi kebisingan, dan fokus pada informasi musikal utama.
- Fungsi
-
Penyesuaian Parameter Model:
- Parameter Tambahan di
predict_and_save: Menambahkan parameter sepertionset_threshold,frame_threshold,minimum_note_length,minimum_frequency, danmaximum_frequencyuntuk meningkatkan akurasi deteksi not dan menyesuaikan sensitivitas model.onset_threshold: Menentukan threshold untuk deteksi onset (awal not).frame_threshold: Menentukan threshold untuk deteksi frame (keberlanjutan not).minimum_note_length: Menentukan durasi minimum not dalam milidetik.minimum_frequency&maximum_frequency: Menyaring not berdasarkan frekuensi minimum dan maksimum yang relevan dengan rentang frekuensi musik yang umum.
- Parameter Tambahan di
-
Pembersihan File Setelah Konversi:
- Menghapus file audio asli dan file audio pra-pemrosesan setelah proses konversi selesai untuk menghemat ruang penyimpanan.
-
Pesan Status yang Lebih Informatif:
- Menambahkan pesan cetak untuk memberikan informasi kepada pengguna tentang tahapan proses yang sedang berlangsung, sehingga pengguna lebih memahami apa yang terjadi selama eksekusi skrip.
-
Penanganan Kesalahan yang Lebih Baik:
- Menangani kemungkinan kesalahan selama proses konversi dan memberikan pesan yang informatif jika terjadi kesalahan.
Langkah Tambahan yang Perlu Dilakukan:
- Instalasi Pustaka Tambahan:
- Pastikan Anda telah menginstal pustaka
librosadansoundfileyang diperlukan untuk pra-pemrosesan audio:pip install librosa soundfile
- Pastikan Anda telah menginstal pustaka
- Pastikan Versi Basic Pitch Terbaru:
- Pastikan Anda menggunakan versi terbaru dari Basic Pitch yang mendukung parameter tambahan yang digunakan.
Tips untuk Hasil yang Lebih Baik:
- Eksperimen dengan Parameter:
- Anda dapat menyesuaikan nilai parameter seperti
onset_threshold,frame_threshold, danminimum_note_lengthsesuai dengan karakteristik lagu yang dikonversi untuk mendapatkan hasil terbaik.
- Anda dapat menyesuaikan nilai parameter seperti
- Kualitas Audio Input:
- Kualitas file audio input sangat mempengaruhi hasil konversi. Pastikan Anda menggunakan file audio dengan kualitas tinggi.
Catatan Penting:
- Hasil konversi dari audio ke MIDI mungkin tidak selalu sempurna, terutama untuk lagu-lagu dengan tekstur kompleks atau instrumen yang tumpang tindih.
- Model konversi audio ke MIDI memiliki keterbatasan dalam menangani polifoni yang kompleks, sehingga hasilnya mungkin berbeda dari harapan.
- Pra-pemrosesan dan penyesuaian parameter dapat membantu, tetapi dalam beberapa kasus, penyempurnaan manual pada file MIDI hasil konversi mungkin diperlukan.
Semoga skrip yang telah ditingkatkan ini membantu Anda menghasilkan file MIDI yang lebih akurat dan sesuai dengan lagu yang Anda konversi!
-