我已经在我的应用中实现了文本到语音转换,它可以正常使用我目前使用的代码。基本上算法创建一个文本,然后如果用户点击UIButton,则说出文本。
挑战:我想启用相同的UIButton来暂停合成器,如果按钮已经被点击(即当前正在说文本),然后继续说话它停止的地方,如果按钮正在被再次点击。
我知道AVFoundation参考中有一些功能,但我无法正确实现它们。
有人知道如何在Swift中执行此操作吗?
import UIKit
import AVFoundation
@IBOutlet var generatedText: UILabel!
@IBAction func buttonSpeakClicked(sender: UIButton){
var mySpeechSynthesizer:AVSpeechSynthesizer = AVSpeechSynthesizer()
var mySpeechUtterance:AVSpeechUtterance = AVSpeechUtterance(string:generatedText.text)
mySpeechUtterance.rate = 0.075
mySpeechSynthesizer .speakUtterance(mySpeechUtterance)
}
答案 0 :(得分:5)
AVSpeechSynthesizer Class Reference
你试过这些方法吗?
- pauseSpeakingAtBoundary:
和- continueSpeaking
这些是一些属性,(paused
和speaking
)可以帮助您确定合成器的状态。
这样的代码应该有效:mySpeechSynthesizer.pauseSpeakingAtBoundary(AVSpeechBoundary.Immediate)
答案 1 :(得分:2)
在Main.storyboard
中,输入两个UIElements
:
UITextView
。UIButton
可以播放,暂停和继续阅读文字。在以下代码中,从outlet
到UITextView
创建一个@IBOutlet
,从action
到UIButton
创建一个@IBAction
。以下代码是一个有效的示例,应为您的ViewController.swift
:
import UIKit
import AVFoundation
class ViewController: UIViewController {
// Synth object
let synth = AVSpeechSynthesizer()
// Utterance object
var theUtterance = AVSpeechUtterance(string: "")
// Text element that the synth will read from.
@IBOutlet weak var textView: UITextView!
// Function that starts reading, pauses reading, and resumes
// reading when the UIButton is pressed.
@IBAction func textToSpeech(_ sender: UIButton) {
// The resume functionality
if (synth.isPaused) {
synth.continueSpeaking();
}
// The pause functionality
else if (synth.isSpeaking) {
synth.pauseSpeaking(at: AVSpeechBoundary.immediate)
}
// The start functionality
else if (!synth.isSpeaking) {
// Getting text to read from the UITextView (textView).
theUtterance = AVSpeechUtterance(string: textView.text)
theUtterance.voice = AVSpeechSynthesisVoice(language: "en-GB")
theUtterance.rate = 0.5
synth.speak(theUtterance)
}
}
// Standard function
override func viewDidLoad() {
super.viewDidLoad()
}
// Standard function
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
答案 2 :(得分:0)
这是如何实现这一目标
首先创建AVSpeechSynthesizer的类变量并将其初始化
let synth = AVSpeechSynthesizer()
这是单击按钮的方法(用于播放音频,如果已经播放则暂停它
@IBAction func onAVButtonClicked(_ sender: Any) {
if synth.isSpeaking {
// when synth is already speaking or is in paused state
if synth.isPaused {
synth.continueSpeaking()
}else {
synth.pauseSpeaking(at: AVSpeechBoundary.immediate)
}
}else{
// when synth is not started yet
let string = attrStr.string
let utterance = AVSpeechUtterance(string: string)
utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
synth.speak(utterance)
}
}