import requests import playsound import tempfile def getgoogletranslatettsurl(text,…
- User
import requests import playsound import tempfile
def get_google_translate_tts_url(text, lang='th'): """Get the URL for Google Translate TTS.""" url = 'https://translate.google.com/translate_tts' params = { 'ie': 'UTF-8', 'q': text, 'tl': lang, 'client': 'gtx' } return url, params
def download_audio(text, lang='th'): """Download audio file from Google Translate.""" url, params = get_google_translate_tts_url(text, lang) response = requests.get(url, params=params, headers={'User-Agent': 'Mozilla/5.0'}) response.raise_for_status() # Raise an exception for HTTP errors
# Save the audio to a temporary file with tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as tmp_file: tmp_file.write(response.content) audio_path = tmp_file.name print(f"Audio saved to {audio_path}") return audio_pathdef play_audio(audio_path): """Play the audio file.""" playsound.playsound(audio_path)
def main(): text = input("Enter Thai text to convert to speech: ") lang = 'th' # Language code for Thai
audio_path = download_audio(text, lang) play_audio(audio_path)if name == 'main': main()
if user input filename with file type make it read from file ex. ep001.txt
- Assistant
To modify your script so that it can read text from a file if the user provides a filename (for example, ), you can adjust the function. Here's the updated code that checks if the input contains a file extension and reads from the specified file if it does:
- User
if not specific file type .txt it mean read frome text input
- Assistant