Skip to content

Instantly share code, notes, and snippets.

@lamegaton
Created September 3, 2018 07:48
Show Gist options
  • Save lamegaton/1c7f383d6434a9b02f5652ddbee258d9 to your computer and use it in GitHub Desktop.
Save lamegaton/1c7f383d6434a9b02f5652ddbee258d9 to your computer and use it in GitHub Desktop.
#python use gtts and pygame to play sound directly
from gtts import gTTS
from io import BytesIO
import pygame
mp3_fp = BytesIO()
tts = gTTS("Trước khi bắt đầu, xin lưu ý \
rằng khi market size của bạn \
nhỏ không có nghĩa rằng đó là \
một mô hình kinh doanh không tốt", 'vi')
tts.write_to_fp(mp3_fp)
mp3_fp.seek(0)
pygame.mixer.init()
pygame.mixer.music.load(mp3_fp)
pygame.mixer.music.play()
@shreyas-jk
Copy link

Not working

@Red-exe-Engineer
Copy link

Not working

Same, no error but nothing is coming out of my speakers :(

@Red-exe-Engineer
Copy link

Red-exe-Engineer commented Sep 12, 2022

while pygame.mixer.music.get_busy():
    pygame.time.Clock().tick(10)

@Red-exe-Engineer
Copy link

One last thing, Pygame seems to use a sample rate of 22050 but gTTS uses 24000, this makes audio sound weird
An easy way to fix this is to add pygame.mixer.pre_init(24000) before the normal mixer init call, here's an example if the difference

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