fix this scippt : 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...")
# Corrected the placeholder to {output-ext}
output_template = os.path.join(tmpdirname, 'downloaded_song.{output-ext}')
code
# Use spotdl to download the song to the temporary directory
subprocess.run([
'spotdl', 'download', song_query,
'--output', output_template
], check=True)
# Look for the downloaded song in the temporary directory
# Fetch the correct file extension
downloaded_files = os.listdir(tmpdirname)
if downloaded_files:
song_file = os.path.join(tmpdirname, downloaded_files[0])
return song_file, tmpdirname # Return the song path and temp directory
else:
print("Failed to download song.")
return None, tmpdirname
except subprocess.CalledProcessError as e:
print(f"An error occurred while downloading the song: {e}")
return None, tmpdirname
def audio_to_midi_with_basic_pitch(audio_file, output_dir):
"""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
code
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
)
print("Conversion complete. MIDI file saved.")
except Exception as e:
print(f"An error occurred during audio to MIDI conversion: {e}")
Assistant
---- Main Program ----
if name == "main":
song_query = input("Enter the song title or Spotify link: ")
code
# Step 1: Download the song
downloaded_song, tmpdirname = download_song_from_spotify(song_query)
if downloaded_song:
# Step 2: Convert audio to MIDI
current_dir = os.getcwd()
print("Converting audio to MIDI...")
audio_to_midi_with_basic_pitch(downloaded_song, current_dir)
# 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.") ,,,because this error : Downloading song...
ffmpeg version 7.1 Copyright (c) 2000-2024 the FFmpeg developers
built with clang version 19.1.0
configuration: --prefix=/d/bld/ffmpeg_1727723574466/_h_env/Library --cc=clang.exe --cxx=clang++.exe --nm=llvm-nm --ar=llvm-ar --disable-doc --enable-openssl --enable-demuxer=dash --enable-hardcoded-tables --enable-libfreetype --enable-libharfbuzz --enable-libfontconfig --enable-libopenh264 --enable-libdav1d --ld=lld-link --target-os=win64 --enable-cross-compile --toolchain=msvc --host-cc=clang.exe --extra-libs=ucrt.lib --extra-libs=vcruntime.lib --extra-libs=oldnames.lib --strip=llvm-strip --disable-stripping --host-extralibs= --disable-libopenvino --enable-gpl --enable-libx264 --enable-libx265 --enable-libaom --enable-libsvtav1 --enable-libxml2 --enable-pic --enable-shared --disable-static --enable-version3 --enable-zlib --enable-libopus --pkg-config=/d/bld/ffmpeg_1727723574466/_build_env/Library/bin/pkg-config
libavutil 59. 39.100 / 59. 39.100
libavcodec 61. 19.100 / 61. 19.100
libavformat 61. 7.100 / 61. 7.100
libavdevice 61. 3.100 / 61. 3.100
libavfilter 10. 4.100 / 10. 4.100
libswscale 8. 3.100 / 8. 3.100
libswresample 5. 3.100 / 5. 3.100
libpostproc 58. 3.100 / 58. 3.100
Splitting the commandline.
Reading option '-nostdin' ... matched as option 'stdin' (enable or disable interaction on standard input) with argument 0.
Reading option '-y' ... matched as option 'y' (overwrite output files) with argument '1'.
Reading option '-i' ... matched as input url with argument 'C:\Users\ZILA.spotdl\temp\QLctCeVaNSw.webm'.
Reading option '-movflags' ... matched as AVOption 'movflags' with argument '+faststart'.
Reading option '-v' ... matched as option 'v' (set logging level) with argument 'debug'.
Reading option '-progress' ... matched as option 'progress' (write program-readable progress information) with argument '-'.
Reading option '-nostats' ... matched as option 'stats' (print progress report during encoding) with argument 0.
Reading option '-codec:a' ... matched as option 'codec' (alias for -c (select encoder/decoder)) with argument 'libmp3lame'.
Reading option '-b:a' ... matched as option 'b' (video bitrate (please use -b:v)) with argument '129k'.
Reading option 'C:\Users\ZILA\AppData\Local\Temp\tmpxh7g1lyh\downloaded_song.mp3' ... matched as output url.
Finished splitting the commandline.
Parsing a group of options: global .
Applying option nostdin (enable or disable interaction on standard input) with argument 0.
Applying option y (overwrite output files) with argument 1.
Applying option v (set logging level) with argument debug.
Applying option progress (write program-readable progress information) with argument -.
[pipe @ 0000025E33A4C480] Setting default whitelist 'crypto,data'
Applying option nostats (print progress report during encoding) with argument 0.
Successfully parsed a group of options.
Parsing a group of options: input url C:\Users\ZILA.spotdl\temp\QLctCeVaNSw.webm.
Successfully parsed a group of options.
Opening an input file: C:\Users\ZILA.spotdl\temp\QLctCeVaNSw.webm.
[AVFormatContext @ 0000025E33AABF00] Opening 'C:\Users\ZILA.spotdl\temp\QLctCeVaNSw.webm' for reading
[file @ 0000025E33A4CCC0] Setting default whitelist 'file,crypto,data'
[matroska,webm @ 0000025E33AABF00] Format matroska,webm probed with size=2048 and score=100
st:0 removing common factor 1000000 from timebase
[matroska,webm @ 0000025E33AABF00] Before avformat_find_stream_info() pos: 532 bytes read:32768 seeks:0 nb_streams:1
Transform tree:
mdct_inv_float_avx2 - type: mdct_float, len: 120, factors[2]: [2, any], flags: [aligned, out_of_place, inv_only]
fft_pfa_15xM_asm_float_avx2 - type: fft_float, len: 60, factors[2]: [15, 2], flags: [aligned, inplace, out_of_place, preshuf, asm_call]
fft4_fwd_asm_float_sse2 - type: fft_float, len: 4, factor: 2, flags: [aligned, inplace, out_of_place, preshuf, asm_call]
Transform tree:
mdct_inv_float_avx2 - type: mdct_float, len: 240, factors[2]: [2, any], flags: [aligned, out_of_place, inv_only]
fft_pfa_15xM_asm_float_avx2 - type: fft_float, len: 120, factors[2]: [15, 2], flags: [aligned, inplace, out_of_place, preshuf, asm_call]
fft8_asm_float_avx - type: fft_float, len: 8, factor: 2, flags: [aligned, inplace, out_of_place, preshuf, asm_call]
Transform tree:
mdct_inv_float_avx2 - type: mdct_float, len: 480, factors[2]: [2, any], flags: [aligned, out_of_place, inv_only]
fft_pfa_15xM_asm_float_avx2 - type: fft_float, len: 240, factors[2]: [15, 2], flags: [aligned, inplace, out_of_place, preshuf, asm_call]
fft16_asm_float_fma3 - type: fft_float, len: 16, factor: 2, flags: [aligned, inplace, out_of_place, preshuf, asm_call]
Transform tree:
mdct_inv_float_avx2 - type: mdct_float, len: 960, factors[2]: [2, any], flags: [aligned, out_of_place, inv_only]
fft_pfa_15xM_asm_float_avx2 - type: fft_float, len: 480, factors[2]: [15, 2], flags: [aligned, inplace, out_of_place, preshuf, asm_call]
fft32_asm_float_fma3 - type: fft_float, len: 32, factor: 2, flags: [aligned, inplace, out_of_place, preshuf, asm_call]
[opus @ 0000025E33ABEAC0] skip 312/960 samples
[matroska,webm @ 0000025E33AABF00] All info found
[matroska,webm @ 0000025E33AABF00] After avformat_find_stream_info() pos: 1118 bytes read:32768 seeks:0 frames:1
Input #0, matroska,webm, from 'C:\Users\ZILA.spotdl\temp\QLctCeVaNSw.webm':
Metadata:
encoder : google/video-file
Duration: 00:02:34.48, start: -0.007000, bitrate: 129 kb/s
Stream #0:0(eng), 1, 1/1000: Audio: opus, 48000 Hz, stereo, fltp, delay 312 (default)
Successfully opened the file.
Parsing a group of options: output url C:\Users\ZILA\AppData\Local\Temp\tmpxh7g1lyh\downloaded_song.mp3.
Applying option codec:a (alias for -c (select encoder/decoder)) with argument libmp3lame.
Applying option b:a (video bitrate (please use -b:v)) with argument 129k.
Successfully parsed a group of options.
Opening an output file: C:\Users\ZILA\AppData\Local\Temp\tmpxh7g1lyh\downloaded_song.mp3.
[out#0/mp3 @ 0000025E33A83400] No explicit maps, mapping streams automatically...
[aost#0:0 @ 0000025E33A8D080] Unknown encoder 'libmp3lame'
[aost#0:0 @ 0000025E33A8D080] Error selecting an encoder
Error opening output file C:\Users\ZILA\AppData\Local\Temp\tmpxh7g1lyh\downloaded_song.mp3.
Error opening output files: Encoder not found
[AVIOContext @ 0000025E33A53940] Statistics: 32768 bytes read, 0 seeks
The error you're encountering indicates that your FFmpeg installation lacks the libmp3lame encoder, which is essential for encoding MP3 files. The specific error message:
code
[aost#0:0 @ ...] Unknown encoder 'libmp3lame'
Error opening output file ... Encoder not found
means that when spotdl tries to convert the downloaded audio to MP3 format, FFmpeg cannot find the necessary encoder to perform the conversion.
Here's how you can fix this issue:
1. Verify Your FFmpeg Installation
First, check whether your current FFmpeg installation includes the libmp3lame encoder.
Steps:
Open Command Prompt:
Press Win + R, type cmd, and press Enter.
Check for libmp3lame Encoder:
Run the following command:
code
ffmpeg -encoders | findstr libmp3lame
If libmp3lame is listed, it means your FFmpeg installation supports MP3 encoding, and the issue might be elsewhere.
If it is not listed, proceed to the next step to install the correct version of FFmpeg.
2. Install FFmpeg with libmp3lame Support
Your current FFmpeg might be a minimal or stripped-down version without MP3 encoding capabilities. Installing a full version of FFmpeg with libmp3lame support should resolve the issue.
For Windows users, you can get ready-to-use builds from Gyan.dev.
Download the GPL Version:
Scroll down to the Windows section.
Under git releases, click on the ffmpeg-git-full.7z link to download the full build. This version includes all encoders and decoders, including libmp3lame.
Extract the Archive:
Use a tool like 7-Zip to extract the contents of the ffmpeg-git-full.7z file.
Extract it to a folder, e.g., C:\ffmpeg.
Add FFmpeg to Your System PATH:
Press Win + R, type sysdm.cpl, and press Enter.
Go to the Advanced tab and click on Environment Variables.
Under System Variables, scroll down and find the Path variable. Select it and click Edit.
Click New and add the path to the FFmpeg bin directory, e.g., C:\ffmpeg\bin.
Click OK on all open dialogs to save the changes.
Verify the Installation:
Close any open Command Prompt windows and open a new one to refresh the environment variables.
Run:
code
ffmpeg -version
You should see the version information for the newly installed FFmpeg.
Check for libmp3lame Again:
Run:
code
ffmpeg -encoders | findstr libmp3lame
You should now see libmp3lame listed among the encoders.
3. Re-run Your Script
With the correct version of FFmpeg installed, your script should be able to download and convert songs without encountering the libmp3lame error.
Note: Ensure that no other FFmpeg versions are conflicting. Remove or update any older FFmpeg installations if necessary.
Additional Tips
Ensure spotdl is Updated:
Run pip install spotdl --upgrade to make sure you have the latest version.
Check Firewall and Antivirus Settings:
Sometimes, security software can interfere with FFmpeg's operation. Ensure that FFmpeg and your script have the necessary permissions.
Test FFmpeg Independently:
To confirm that FFmpeg can encode MP3 files, try converting a sample audio file manually:
Replace input_audio_file.webm with a valid audio file path.
Understanding the Issue
The core of the problem lies in FFmpeg's ability to encode in MP3 format using the libmp3lame encoder. Without this encoder, any attempt to convert audio to MP3 will fail with the error you've encountered.
By ensuring that your FFmpeg installation includes libmp3lame, you're enabling spotdl (which relies on FFmpeg for media processing) to perform the required conversions successfully.
Your Updated Script
No changes to your script are necessary after fixing the FFmpeg installation. However, always ensure that your dependencies and external tools are correctly installed and configured.
I hope this helps you resolve the issue! If you have any more questions or need further assistance, feel free to ask.