You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

2024年Swift中如何通过API获取并使用多类型语音合成语音?

在Swift中获取并使用多语种/个性化文本转语音语音(2024年方案)

旧的文本转语音实现仅能通过语言代码指定单一语音,无法利用苹果后续新增的多音色、自定义及个性化语音。2024年可通过以下API实现对这类丰富语音的编程访问:

一、获取所有可用语音

使用AVSpeechSynthesisVoice.speechVoices()方法可获取系统中全部可用语音,包括官方新增的男女声、用户创建的专属语音等。每个AVSpeechSynthesisVoice实例包含关键属性:

  • identifier: 语音唯一标识(如com.apple.ttsbundle.Alex-compact)
  • name: 语音名称(如"Alex"、"Samantha")
  • language: 对应语言代码(如"en-US")
  • quality: 语音质量等级(.default/.enhanced/.premium等)

示例代码:

// 获取所有系统可用语音
let allVoices = AVSpeechSynthesisVoice.speechVoices()

// 筛选英语系语音
let englishVoices = allVoices.filter { $0.language.hasPrefix("en") }

// 输出语音信息
for voice in englishVoices {
    print("名称: \(voice.name), 标识: \(voice.identifier), 语言: \(voice.language)")
}

二、直接指定特定语音

若已知目标语音的唯一标识,可通过AVSpeechSynthesisVoice(identifier:)直接初始化。系统提供了部分预定义常量,比如AVSpeechSynthesisVoiceIdentifier.alex、AVSpeechSynthesisVoiceIdentifier.samantha:

// 使用Samantha语音
if let samanthaVoice = AVSpeechSynthesisVoice(identifier: AVSpeechSynthesisVoiceIdentifier.samantha) {
    let utterance = AVSpeechUtterance(string: "Hello, this is Samantha speaking.")
    utterance.voice = samanthaVoice
    utterance.rate = 0.5
    
    let synthesizer = AVSpeechSynthesizer()
    synthesizer.speak(utterance)
}

三、获取用户自定义个性化语音

用户通过系统设置创建的专属个性化语音,可通过筛选isCustom属性识别:

// 筛选所有用户自定义语音
let customVoices = allVoices.filter { $0.isCustom }

if let myCustomVoice = customVoices.first {
    let utterance = AVSpeechUtterance(string: "这是我的专属语音")
    utterance.voice = myCustomVoice
    
    let synthesizer = AVSpeechSynthesizer()
    synthesizer.speak(utterance)
}

四、访问VoiceOver相关语音

若需调用VoiceOver使用的语音,可使用UIKit框架下的UIAccessibilitySpeechSynthesisVoice:

import UIKit

// 获取当前VoiceOver使用的语音
if let voiceOverVoice = UIAccessibilitySpeechSynthesisVoice.currentVoice() {
    let utterance = AVSpeechUtterance(string: "这是VoiceOver使用的语音")
    utterance.voice = voiceOverVoice
    
    let synthesizer = AVSpeechSynthesizer()
    synthesizer.speak(utterance)
}

内容的提问来源于stack exchange,提问作者user6631314

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 00:55:13