如何在Mac OS X终端修改默认语音?避免重复修改Python代码
Got it, let's solve this without having to edit every single os.system("say 'Foo'") line in your Python code. Here are a few solid options tailored for Mac OS X High Sierra 10.13.3:
Option 1: Change the System-Wide Default Voice (Easiest, No Code Changes)
This is the most straightforward approach—set your preferred voice as the system default, and every say command (including those in your Python script) will use it automatically.
- Open System Preferences → Accessibility → Speech
- Under the "System Voice" dropdown menu, select the voice you want to use (e.g., Samantha, Victoria, or any other installed voice)
- Test it out: open Terminal and run
say 'Hello world'—it should use your new default voice. Your Python script’sos.system("say 'Foo'")calls will pick up this change instantly, no code edits required.
Option 2: Override os.system in Python (Script-Specific, No System Changes)
If you don’t want to change the system-wide default but only want your Python script to use a specific voice, you can monkey-patch the os.system function to automatically add the -v flag to say commands.
Add this code at the very top of your Python script (before any other os.system calls):
import os # Save a reference to the original os.system function original_system = os.system def custom_say_handler(command): # Check if the command is a simple "say '...'" call if command.startswith("say '") and command.endswith("'"): # Replace 'Samantha' with your desired voice preferred_voice = "Samantha" # Modify the command to include the voice flag modified_command = f"say -v '{preferred_voice}' {command[4:]}" return original_system(modified_command) # For all other commands, use the original os.system behavior return original_system(command) # Replace the default os.system with our custom version os.system = custom_say_handler
Now every os.system("say 'Foo'") line in your script will automatically use your chosen voice, no need to edit each line individually.
Option 3: Use a Shell Alias (For Terminal/Shell Contexts)
If you want the say command to use your preferred voice everywhere in the shell (including when your script runs), you can set up a shell alias:
- Open your shell configuration file. For High Sierra’s default bash shell, this is
~/.bash_profile. - Add this line, replacing
Samanthawith your desired voice:alias say='say -v Samantha' - Save the file and run
source ~/.bash_profileto apply the changes immediately.
Note: Since os.system uses /bin/sh by default, you may need to ensure your alias is loaded in the sh environment. Alternatively, you can modify your Python script to use bash explicitly (though this requires editing os.system calls, so Options 1 or 2 are better for avoiding code changes).
内容的提问来源于stack exchange,提问作者user9311010

