desbma / GoogleSpeech

Read text using Google Translate TTS API
GNU Lesser General Public License v2.1
161 stars 37 forks source link

save to BytesIO #18

Closed goldengrape closed 5 years ago

goldengrape commented 5 years ago

Is it possible to save mp3 to BytesIO? I tried this:

from io import BytesIO
from google_speech import Speech

# say "Hello World"
text = "Hello World"
lang = "en"
speech = Speech(text, lang)
speech.play()

mp3_fp = BytesIO()
speech.save(mp3_fp)

but failed I got invalid file: <_io.BytesIO object at 0x1090d2990>

goldengrape commented 5 years ago

consider this:

    def save(self, path):
        """ Save audio data to file or BytesIO. """
        if isinstance(path, str):
            with open(path, "wb") as f:
                for segment in self:
                    f.write(segment.getAudioData())

        if isinstance(path, BytesIO):
            for segment in self:
                path.write(segment.getAudioData())
desbma commented 5 years ago

It should work with https://github.com/desbma/GoogleSpeech/commit/3827e3225e5897f47165cc61169c77aed2b70ef5