构建语音助手时如何将pyttsx3语音设置为男声?调整语速与频率无效的解决及代码修改方案
Hey there! The issue you’re facing is that pyttsx3 defaults to the first available voice on your system, which happens to be female. To switch to a male voice, you need to explicitly select one from the list of installed voices on your machine. Here’s how to modify your code:
Step 1: Identify Available Voices (Optional but Helpful)
First, let’s print out all voices installed on your system so you can spot the male one. Add this snippet right after initializing the engine:
# Get list of available voices voices = engine.getProperty('voices') # Print details of each voice to find the male option for voice in voices: print(f"Voice ID: {voice.id}") print(f"Name: {voice.name}") print(f"Language: {voice.language}\n")
Running this will show entries like (example on Windows):
Voice ID: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_DAVID_11.0
Name: Microsoft David Desktop - English (United States)
Language: en-us
Step 2: Update Code to Use Male Voice
Once you’ve identified the male voice’s ID or index, update your code to set that voice. Here’s the full modified version:
import speech_recognition as sr import pyttsx3 listener = sr.Recognizer() engine = pyttsx3.init() # Set male voice (adjust index or use exact ID from your system's output) voices = engine.getProperty('voices') # Example: Use the second voice (common for male on Windows) or replace with your male voice ID engine.setProperty('voice', voices[1].id) # Optional: Tweak rate and volume if needed engine.setProperty('rate', 150) # Lower = slower, higher = faster engine.setProperty('volume', 0.9) # Range: 0.0 to 1.0 engine.say('Hello, I am your male voice assistant') engine.say('What can I help you with?') engine.runAndWait() try: with sr.Microphone() as source: print('listening...') voice = listener.listen(source) command = listener.recognize_google(voice) command = command.lower() if 'hey vocal' in command: print(command) except: pass
Key Notes:
- The voice index (like
voices[1]) might vary on your system—use the earlier print snippet to find the correct one, or paste the exact voice ID string instead of the index. - If no male voice shows up in the list, install one:
- Windows: Go to Settings → Time & Language → Speech → Add voices, then select a male English voice.
- macOS: Open System Preferences → Accessibility → Speech, then pick a male voice from the dropdown.
- Linux: Install additional espeak voices (e.g.,
espeak-ngpackages), then check available options withespeak --voices.
That should get your assistant talking in a male voice right away!
内容的提问来源于stack exchange,提问作者Aniket M

