简体   繁体   中英

How to play a audio file on HTML page from a zipfile which contains .wav file in memory?

I am building a webapp where I will get a zipfile from API call. This Zipfile contains an audio file which I have to play on the browser. I can't store the audio files on server and read them back.

This is my flask webpage, which renders download.html webpage.

zipped_file = io.BytesIO(out_bytes) 
with ZipFile(zipped_file, 'r') as zf:
        zf.printdir()
        filename = zf.infolist()[0].filename
        buff = zf.read(filename) 

 return render_template('download.html', value = buff)

In download.html I have to play the audio from file we unzipped.

<audio controls controlsList="nodownload">
   <source src="{{value}}">
   Your browser does not support the audio element.
 </audio>

I am new to flask, if you have any ideas on how to play an audio without storing it in server please let me know.

Thanks.

You should be able to base64 encode your buff bytes, then prefix your src attribute with data:audio/wav;base64, :

import base64
zipped_file = io.BytesIO(out_bytes) 
with ZipFile(zipped_file, 'r') as zf:
    zf.printdir()
    filename = zf.infolist()[0].filename
    buff = zf.read(filename)
    encoded = base64.b64encode(buff)

return render_template('download.html', value = encoded)
<audio controls controlsList="nodownload">
    <source src="data:audio/wav;base64,{{value}}">
    Your browser does not support the audio element.
</audio>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM