How to use file in-memory?

1.2k Views Asked by At

The following code currently saves the file to disk. Can I save it to memory instead?

def synthesize(iam_token, text):
    url = 'https://example.com/tts:synthesize'
    headers = {
        'Authorization': 'Bearer ' + iam_token,
    }

    data = {
        'text': text
    }

    with requests.post(url, headers=headers, data=data, stream=True) as resp:
        for chunk in resp.iter_content(chunk_size=None):
            yield chunk


with open('/tmp/tts.ogg', 'wb') as f:
    for audio_content in synthesize(iam_token, text):
        f.write(audio_content)
1

There are 1 best solutions below

0
On

Just use the BytesIO object from the io package.

import io

buffer = io.BytesIO()
for audio_content in sythesize(iam_token,text):
    buffer.write(audio_content)