How to make Python speak

前端 未结 13 1191
时光说笑
时光说笑 2020-11-30 20:34

How could I make Python say some text?

I could use Festival with subprocess but I won\'t be able to control it (or maybe in interactive mode, but it won\'t be clean)

13条回答
  •  情深已故
    2020-11-30 20:42

    Combining the following sources, the following code works on Windows, Linux and macOS using just the platform and os modules:

    • cantdutchthis' answer for the mac command
    • natka_m's comment for the Ubuntu command
    • BananaAcid's answer for the Windows command
    • Louis Brandy's answer for how to detect the OS
    • nc3b's answer for how to detect the Linux distribution
    tx = input("Text to say >>> ")
    tx = repr(tx)
    
    import os
    import platform
    
    syst = platform.system()
    if syst == 'Linux' and platform.linux_distribution()[0] == "Ubuntu":
        os.system('spd-say %s' % tx)
    elif syst == 'Windows':
        os.system('PowerShell -Command "Add-Type –AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak(%s);"' % tx)
    elif syst == 'Darwin':
        os.system('say %s' % tx)
    else:
        raise RuntimeError("Operating System '%s' is not supported" % syst)
    

    Note: This method is not secure and could be exploited by malicious text.

提交回复
热议问题