Forums

Using ffmpeg with pydub

My web app uses the package pydub, which depends on ffmpeg. My code converts a user-submitted audio file to mp3 and then saves it to the database. Locally, this code is working great, however I am getting an error when it's on pythonanywhere. I am wondering if there is anything I have to do to access ffmpeg.

Below is my code that uses the pydub package (and depends on ffmpeg), which works locally but not on pythonanywhere:

# Create export path based on current audio file path and filename
filename_no_ext = Path(str(tile.audio)).stem
new_filename = f"{filename_no_ext}_x.mp3"
export_path = f"media/gridsquid/aud/{request.user.id}/{tile.grid.id}/{new_filename}"
tile_path = f"gridsquid/aud/{request.user.id}/{tile.grid.id}/{new_filename}"

# Convert audio file to mp3 using pydub                    
sound = AudioSegment.from_file(tile.audio.path)
sound.export(export_path, format="mp3", bitrate="128k")

# Replace original audio file with converted mp3
tile.audio.delete()
tile.audio = tile_path
tile.save()
new_filename = os.path.basename(tile.audio.name)
print(f"{filename} converted to mp3 and replaced with {new_filename}")

Below is the error from the error log, showing which line is throwing the error:

2022-11-14 23:17:27,548: Internal Server Error: /add_audio/15 Traceback (most recent call last): File "/home/gridsquid/.virtualenvs/myvirtualenv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request)

File "/home/gridsquid/.virtualenvs/myvirtualenv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, callback_args, *callback_kwargs)

File "/home/gridsquid/gridsquid/gridsquid/views.py", line 967, in add_audio

sound.export(export_path, format="mp3", bitrate="128k")

File "/home/gridsquid/.virtualenvs/myvirtualenv/lib/python3.10/site-packages/pydub/audio_segment.py", line 867, in export out_f, _ = _fd_or_path_or_tempfile(out_f, 'wb+')

File "/home/gridsquid/.virtualenvs/myvirtualenv/lib/python3.10/site-packages/pydub/utils.py", line 60, in _fd_or_path_or_tempfile fd = open(fd, mode=mode)

FileNotFoundError: [Errno 2] No such file or directory: 'media/gridsquid/aud/1/2/003_03-bear_sklwb9q_x.mp3'

Any advice would be greatly appreciated.

I figured it out - my code was trying to export to a path that was not found. I had to add /home/my_app/my_app/ to the path go get it to work, which was different than how it was working locally.

Glad to hear that you were able to fix it!