git clone https://github.com/codingstark-dev/videotomp3.gitThe endpoint uses the moviepy library to extract the audio from the video at the provided URL, saves it as an MP3 file, reads the file as bytes, removes the file, and returns the bytes as a response with the MIME type audio/mpeg.
Here is a breakdown of the code:
fromflaskimportFlask, request, Responseimportmoviepy.editorasmpimportioimportosapp=Flask(__name__)
@app.route('/convert', methods=['GET'])defconvert():
video_url=request.args.get('url')
# video_url = request.query_string['video_url']video=mp.VideoFileClip(video_url)
audio=video.audioaudio_path=os.path.join(os.getcwd(), 'audio.mp3')
audio.write_audiofile(audio_path)
withopen(audio_path, 'rb') asf:
audio_bytes=f.read()
os.remove(audio_path)
returnResponse(audio_bytes, mimetype="audio/mpeg")
if__name__=='__main__':
app.run()