iOS文字转语音Api

Jes*_*sse 50 text-to-speech ios siri

我似乎无法找到任何相关的东西.在iOS7中是否有任何Siri类或API可以让您进行文本到语音转换?我想要做的就是以下内容:

[siriInstance say:@"This is a test"];
Run Code Online (Sandbox Code Playgroud)

然后让Siri从我的应用程序中说出来.

看来我们应该有能力做到这一点,不是吗?看起来像是一件微不足道的事情.

Ali*_*bas 144

从iOS 7开始,您就有了新的TTS Api.

在目标C中

AVSpeechSynthesizer *synthesizer = [[AVSpeechSynthesizer alloc]init];
AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:@"Some text"];
[utterance setRate:0.2f];
[synthesizer speakUtterance:utterance];
Run Code Online (Sandbox Code Playgroud)

在斯威夫特

let synthesizer = AVSpeechSynthesizer()
let utterance = AVSpeechUtterance(string: "Some text")
utterance.rate = 0.2
Run Code Online (Sandbox Code Playgroud)

你也可以改变这样的声音:

utterance.voice = AVSpeechSynthesisVoice(language: "fr-FR")
Run Code Online (Sandbox Code Playgroud)

然后说

  • 在Swift 2中 synthesizer.speakUtterance(utterance)

  • 在Swift 3中 synthesizer.speak(utterance)

别忘了 import AVFoundation

有用的方法

您可以使用以下两种方法停止或暂停所有语音:

- (BOOL)pauseSpeakingAtBoundary:(AVSpeechBoundary)boundary;
- (BOOL)stopSpeakingAtBoundary:(AVSpeechBoundary)boundary;
Run Code Online (Sandbox Code Playgroud)

AVSpeechBoundary指示如果语音应暂停或停止立即(AVSpeechBoundaryImmediate),或者它应该暂停或单词目前正在发言后停止(AVSpeechBoundaryWord).

检查AVSpeechSynthesizer文档


Mat*_*son 9

这是Ali ABBAS在操场上使用的答案:

import UIKit
import AVKit
import AVFoundation
import PlaygroundSupport

var str = "Hello, playground"

let synthesizer = AVSpeechSynthesizer()
let utterance = AVSpeechUtterance(string: str)
utterance.rate = 0.4
utterance.voice = AVSpeechSynthesisVoice(language: "en-US")

//for playground only
let playerViewController = AVPlayerViewController()
PlaygroundPage.current.liveView = playerViewController.view
//

synthesizer.speak(utterance)    
Run Code Online (Sandbox Code Playgroud)