| import librosa |
| import numpy as np |
| import matplotlib.pyplot as plt |
| import librosa.display |
| import soundfile as sf |
| import os |
| from pydub import AudioSegment |
|
|
| def preprocess_audio(audio_file): |
| sound = AudioSegment.from_mp3(audio_file) |
| wav_file = audio_file.rsplit('.',1)[0]+'.wav' |
| sound.export(wav_file, format="wav" ) |
| return wav_file |
| |
| def extract_melody(audio_file,output_folder): |
| try: |
| |
| audio_file = preprocess_audio(audio_file) |
| |
| |
| y, sr = librosa.load(audio_file) |
|
|
| |
| y_harmonic, y_percussive = librosa.effects.hpss(y) |
| |
| |
| y_harmonic, y_percussive = librosa.effects.harmonic(y) |
| |
| |
| chroma = librosa.feature.chroma_cqt(y=y_harmonic, sr=sr) |
| |
| |
| plt.figure(figsize=(10, 4)) |
| librosa.display.specshow(chroma, y_axis='chroma', x_axis='time') |
| plt.colorbar() |
| plt.title('Chromagram') |
| plt.tight_layout() |
| plt.show() |
|
|
| |
| base_name = os.path.splitext(os.path.basename(audio_file))[0] |
| output_file = os.path.join(output_folder, f'extracted_melody_{base_name}.wav') |
| sf.write(output_file, y_harmonic, sr) |
| print(f"Extracted melody saved to: {output_file}") |
| except Exception as e: |
| print(f"An error occurred: {e}") |
|
|
| |
| audio_file = 'your_song.mp3' |
| extract_melody(audio_file) |