当我在模拟器中运行时,我使用我的项目AVSpeechUtterance进行文本到语音转换的所有工作都很好,但是当我在我的设备中运行时,语音音量非常慢,这里是我的代码……
let utterance = AVSpeechUtterance(string: "Good night all")
if UserDefaults.standard.string(forKey: "LNG") == "Eng"
{
utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
}
else
{
utterance.voice = AVSpeechSynthesisVoice(language: "de-DE")
}
utterance.rate = AVSpeechUtteranceDefaultSpeechRate
utterance.volume = 1
let synth = AVSpeechSynthesizer()
synth.speak(utterance)发布于 2021-10-07 22:11:20
对于不同的设备,默认值可能不同。你查过了吗?
您可以通过转到Settings>Accessibility>Spoken Content来查看设备的设置
让用户有机会调整这个速率,因为理想的速率对于很多人来说可能是不同的
import SwiftUI
import Speech
class SpeechManager:ObservableObject{
//The default value is likely different for the devices
//You can also look up what the device has set by going to Settings>Accessibility>Spoken Content
var defaultRate = AVSpeechUtteranceDefaultSpeechRate
//Stuff like this is the intended use of UserDefaults
var userSpeechRate: Float{
get{
UserDefaults.standard.value(forKey: "userSpeechRate") as? Float ?? AVSpeechUtteranceDefaultSpeechRate
}
set{
UserDefaults.standard.set(newValue, forKey: "userSpeechRate")
objectWillChange.send()
}
}
//You can save the volume too.
//If your device doesn't respond to this change it is likely a hardware issue or a specific setting on the device.
//Something like the device volume and Silent mode button being off
var userSpeechVolume: Float{
get{
UserDefaults.standard.value(forKey: "userSpeechVolume") as? Float ?? 1
}
set{
UserDefaults.standard.set(newValue, forKey: "userSpeechVolume")
objectWillChange.send()
}
}
//This is mostly your code with the exception of setting a custom rate
func sayGoodNight(){
let utterance = AVSpeechUtterance(string: "Good night all")
if UserDefaults.standard.string(forKey: "LNG") == "Eng"
{
utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
}
else
{
utterance.voice = AVSpeechSynthesisVoice(language: "de-DE")
}
//Change this to use the
utterance.rate = userSpeechRate
utterance.volume = userSpeechVolume
let synth = AVSpeechSynthesizer()
synth.speak(utterance)
}
}
struct SpeechView: View {
@StateObject var vm: SpeechManager = SpeechManager()
var body: some View {
VStack{
Text("default rate \(vm.defaultRate)")
Text("user rate \(vm.userSpeechRate)")
Slider(value: $vm.userSpeechRate, in: 0...1, label: {Text("speech rate")})
Slider(value: $vm.userSpeechVolume, in: 0...1, label: {Text("speech volume")})
Button("say goodnight", action: {
vm.sayGoodNight()
})
}
}
}
struct SpeechView_Previews: PreviewProvider {
static var previews: some View {
SpeechView()
}
}https://stackoverflow.com/questions/49776409
复制相似问题