pythonflaskaudioffmpegpydub

How to retrieve mediainfo from raw data in Flask app?


I'm uploading an audio file via Flask's FileField form and I want to get to its mediainfo. Uploaded audio is available in the form of bytrs.

To obtain a path for pydub.utils.mediainfo function, I was trying:

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    audiofile = form.file.data.read()
    # type(audiofile) == bytes

    with tempfile.NamedTemporaryFile(mode='w+b', suffix='.mp3') as tmp:
        tmp.write(audiofile)
        # tmp.name == C:\Users\JUSTME~1\AppData\Local\Temp\tmp0wky2_wq.mp3
        print(pydub.utils.mediainfo(tmp.name))

But pydub.utils.mediainfo returns an empty dict object. Is it possible to solve the problem?

Inspired by this quastion.


Solution

  • The issue is that you're trying to read from a file that is also being written to. You can try to use tempfile.mkstemp instead:

    @app.route('/upload', methods=['GET', 'POST'])
    def upload():
        audiofile = form.file.data.read()
    
        fd, path = tempfile.mkstemp(suffix='.mp3')
    
        try:
            with os.fdopen(fd, 'wb') as tmp:
                tmp.write(audiofile)
    
            print(pydub.utils.mediainfo(path))
        finally:
            # Manually clean up the temporary file
            os.remove(path)