How to convert text to speech for OSX in Swift pla

2020-07-17 06:52发布

问题:

I'm trying to learn how to do text to speech for OSX (not iOS) in Swift. I have a playground with code:

import Cocoa

let synth = NSSpeechSynthesizer()
synth.startSpeaking( "Hello World" )

Which seems to run, but no sound occurs. In Xcode, there is a little blue triangle in the lower left corner, which I press thinking it might do something, but sadly no:

Any ideas how to convert text to speech for OSX in a Swift playground? Thanks in advance!

回答1:

NSSpeechSynthesizer's .startSpeaking needs to execute in a background task, but by default this is not possible in a Playground.

You can enable it by importing PlaygroundSupport and setting asynchronous mode, like this:

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true