Home > OS >  open external file through wave.open in python
open external file through wave.open in python

Time:12-17

I'm using wave.open to open file , if i give local path

async def run_test(uri):
        async with websockets.connect(uri) as websocket:
     wf = wave.open('test.wav', "rb")

then it is working but if i give external path it is not working

async def run_test(uri):
        async with websockets.connect(uri) as websocket:
     wf = wave.open('http://localhost:8000/storage/uploads/test.wav', "rb")

getting this error :

OSError: [Errno 22] Invalid argument: 'http://localhost:8000/storage/uploads/test.wav'

CodePudding user response:

Yeah, wave.open() doesn't know anything about HTTP.

You'll need to download the file first, e.g. with requests (or aiohttp or httpx since you're in async land).

import io, requests, wave

resp = requests.get('http://localhost:8000/storage/uploads/test.wav')
resp.raise_for_status()
bio = io.BytesIO()  # file-like memory buffer
bio.write(resp.content)  # todo: if file can be large, maybe use streaming
bio.seek(0)  # seek to the start of the file
wf = wave.open(bio, "rb")  # wave.open accepts file-like objects

This assumes the file is small enough to fit in memory; if it's not, you'd want to use tempfile.NamedTemporaryFile instead.

  • Related