Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can I open() a AudioSegment without exporting the file? #270

GabrielDrapor opened this issue Apr 27, 2018 · 2 comments

Can I open() a AudioSegment without exporting the file? #270

GabrielDrapor opened this issue Apr 27, 2018 · 2 comments


Copy link

GabrielDrapor commented Apr 27, 2018

Expected behavior

I have an AudioSegement, after processing, I want to open() it for some reason, but all I can do now is:

from pydub import AudioSegment

audio = AudioSegment.from_file(path)
audio = speed_change(audio, speed)
audio.export('_'+file_name, format=format)
f = open('_'+file_name, 'rb')

Is there any better way?

Copy link

jaden-young commented Jun 19, 2018

It depends on what data you want. You probably want the fully exported file, headers and all. If you're trying to avoid writing the file out to disk, then reading it back in, you could write to an in-memory buffer using io.BytesIO:

import io
buf = io.BytesIO()
audio.export(buf, format=format)

The above will get you the same result as your code, but without writing to disk.
If you wanted to actually open() the file instead of reading it all at once, just do a, and buf will normally sub right in anywhere you expect a file handle opened as 'rb'.

There is a bit of a nuance on the export though. You do actually have access to the raw bytes of the audio file through AudioSegment.raw_data. However, this doesn't contain the oh-so-valuable header information. If you just do something like:

# won't work well.
with open('garbage.wav', 'wb') as f:

No program is going to able to read garbage.wav, but should you really want those bytes for other purposes, they're just a .raw_data away.

Copy link

GabrielDrapor commented Jun 20, 2018

@jaden-young Very helpful, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet
None yet

No branches or pull requests

2 participants