ajoy0071998 commited on
Commit
7bdbbf4
·
verified ·
1 Parent(s): 0552130

Upload male_voice.py

Browse files
Files changed (1) hide show
  1. male_voice.py +45 -7
male_voice.py CHANGED
@@ -1,12 +1,50 @@
 
 
 
 
 
1
 
2
- import edge_tts
 
 
 
 
 
 
 
3
 
4
- voice = "en-US-GuyNeural" # male voice
5
- rate = "+0%"
 
 
 
 
 
 
 
6
 
7
- async def text_to_speech(text, filename):
8
- communicate = edge_tts.Communicate(text, voice=voice, rate=rate)
9
- await communicate.save(filename)
10
- print(f"Audio saved as {filename}")
11
 
 
 
 
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # male_voice.py
2
+ import pyttsx3
3
+ from pathlib import Path
4
+ import asyncio
5
+ from typing import Union
6
 
7
+ def text_to_speech(text: str, output_path: Union[str, Path]) -> bool:
8
+ """
9
+ Convert text to speech and save to file using pyttsx3.
10
+ Returns True on success.
11
+ """
12
+ try:
13
+ engine = pyttsx3.init()
14
+ engine.setProperty('rate', 150) # Speaking speed
15
 
16
+ # Select male voice (prioritize David, then any non-Zira)
17
+ voices = engine.getProperty('voices')
18
+ selected = False
19
+ for voice in voices:
20
+ name = voice.name.lower()
21
+ if 'david' in name or ('male' in name and 'zira' not in name):
22
+ engine.setProperty('voice', voice.id)
23
+ selected = True
24
+ break
25
 
26
+ if not selected and voices:
27
+ engine.setProperty('voice', voices[0].id) # fallback
 
 
28
 
29
+ # Ensure output path is Path object
30
+ output_path = Path(output_path)
31
+ output_path.parent.mkdir(parents=True, exist_ok=True)
32
 
33
+ # Save to file
34
+ engine.save_to_file(text, str(output_path))
35
+ engine.runAndWait()
36
+
37
+ print(f"[pyttsx3] Saved: {output_path}")
38
+ return True
39
+
40
+ except Exception as e:
41
+ print(f"[pyttsx3] Error: {e}")
42
+ return False
43
+
44
+
45
+ async def text_to_speech_async(text: str, output_path: Union[str, Path]) -> bool:
46
+ """
47
+ Async wrapper for text_to_speech using asyncio.to_thread.
48
+ Prevents blocking the Streamlit event loop.
49
+ """
50
+ return await asyncio.to_thread(text_to_speech, text, output_path)