我已经在我的应用程序中实现了文本到语音,它与我目前使用的代码工作得很好。基本上,algo会创建一个文本,然后如果用户单击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)
}发布于 2015-04-09 18:14:27
你试过这些方法吗?- pauseSpeakingAtBoundary:和- continueSpeaking
这些属性(paused和speaking )可以帮助您确定合成器的状态。
这样的代码应该可以工作:mySpeechSynthesizer.pauseSpeakingAtBoundary(AVSpeechBoundary.Immediate)
发布于 2018-09-22 21:07:02
在Main.storyboard中,使两个UIElements:
UITextView。UIButton。在下面的代码中,从UITextView创建一个UITextView到@IBOutlet,从UIButton创建一个action到@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()
}
}发布于 2019-03-12 12:41:48
在这里,你如何做到这一点?
首先创建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)
}
}https://stackoverflow.com/questions/26038749
复制相似问题