简体   繁体   中英

python io.BytesIO and pygame.mixer

I am loading an audio mp3 file into a python io.BytesIO buffer.

I want then to play this audio file several times with pygame.mixer.

It works fine the first time, but it seems that pygame.mixer.music.play deletes the buffer.

Here is the source code:

import io
import time
import pygame

with open(path_to_my_mp3_file, 'rb') as in_file:
  buffer = io.BytesIO(in_file.read())

pygame.mixer.init()

pygame.mixer.music.load(buffer)
pygame.mixer.music.play()  # works fine !

time.sleep(1)

pygame.mixer.music.load(buffer) # the buffer seems to be cleared
pygame.mixer.music.play()  

I get this error:

  File "test.py", line 17, in <module>
    pygame.mixer.music.load(buffer)
pygame.error: Couldn't read from RWops

Any idea?

Thanks

PS:

I tried this:

with open(path_to_my_mp3_file, 'rb') as in_file:
  buffer = in_file.read()

pygame.mixer.init()

pygame.mixer.music.load(io.BytesIO(buffer))
pygame.mixer.music.play()

time.sleep(1)

pygame.mixer.music.load(io.BytesIO(buffer))
pygame.mixer.music.play()

It works, but i think this code is less performant

BytesIO is a file-like object; so, as any streaming file, it has a position, where all read-write operations take place. Because you've just read data from it, the position is at end, and further reading does nothing; you should rewind it with

buffer.seek(0)

between loading it into music. But you don't need to load it twice, because pygame.mixer.music object itself has rewind() method:

pygame.mixer.music.rewind() # to the beginning

But it is also not needed here, because play() method... rewinds the music to the beginning!

pygame.mixer.music.load(buffer)
pygame.mixer.music.play()  # works fine !

time.sleep(1)

pygame.mixer.music.play()   # and play it again!

that easy!

This worked to me

from io import BytesIO
import pygame

def speak():
    mp3_fp = BytesIO()
    tts = gTTS('hello', lang='en')
    tts.write_to_fp(mp3_fp)
    # mp3_fp.seek(0)
    # return this to the client side.
    return mp3_fp

pygame.init()
pygame.mixer.init()
sound = speak()
sound.seek(0)
pygame.mixer.music.load(sound, "mp3")
pygame.mixer.music.play()

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