Python Text to Speech in Macintosh

可紊 提交于 2019-11-30 04:00:19
rien333

Wouldn't it be much simpler to do this?

from os import system
system('say Hello world!')

You can enter man say to see other things you can do with the say command.

However, if you want some more advanced features, importing AppKit would also be a possibility, although some Cocoa/Objective C knowledge is needed.

from AppKit import NSSpeechSynthesizer
speechSynthesizer = NSSpeechSynthesizer.alloc().initWithVoice_("com.apple.speech.synthesis.voice.Bruce")
speechSynthesizer.startSpeakingString_('Hi! Nice to meet you!')

If you would like to see more things you can do with NSSpeechSynthesizer take a look at Apple's documentation: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSSpeechSynthesizer_Class/Reference/Reference.html

If you are targeting Mac OS X as your platform - PyObjC and NSSpeechSynthesizer is your best bet.

Here is a quick example for you

#!/usr/bin/env python

from  AppKit import NSSpeechSynthesizer
import time
import sys


if len(sys.argv) < 2:
   text = raw_input('type text to speak> ')
else:
   text = sys.argv[1]

nssp = NSSpeechSynthesizer

ve = nssp.alloc().init()

for voice in nssp.availableVoices():
   ve.setVoice_(voice)
   print voice
   ve.startSpeakingString_(text)

   while not ve.isSpeaking():
      time.sleep(0.1)

   while ve.isSpeaking():
      time.sleep(0.1)

Please note that AppKit module is part of PyObjC bridge and should be already installed on your Mac. No need to install it if you are using OS provided python (/usr/bin/python)

theguy

This might work:

import subprocess
subprocess.call(["say","Hello World! (MESSAGE)"])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!