跳到主要内容

文本转语音

通过所选 AI 服务商合成文本,并接收可由 App 播放或进一步处理的本地音频文件。

前提条件

  • AIBudsAISDK 已初始化,并已选择注册的服务商。
  • 服务商支持 TTSServiceAPI
  • 需要时服务商鉴权和网络访问均可用。
  • 按照公开 SDK 契约要求,从后台线程调用合成。

使用 AI 辅助实现

使用 AI 开发

让 AI 帮助实现此工作流

使用官方“实现 AIBuds 文本转语音”技能,根据你的 App 完成实现。

请阅读并遵循 https://docs-aibuds.github.io/zh-Hans/skills/implement-aibuds-text-to-speech,使用该技能在当前 iOS 项目中完成“实现 AIBuds 文本转语音”,并验证结果。
查看官方技能

API 参考

框架

AIBudsAI.xcframework

导入

Swift
import AIBudsAI
import AIBudsAIFoundation

声明

Swift
/// Synthesizes text into speech.
/// - Parameters:
///   - text: The text to synthesize.
///   - config: The synthesis configuration.
///   - completion: Called with the task identifier, success state, optional
///     result, and optional error when synthesis completes.
/// - Important: Call this method from a background thread to avoid blocking
///   the main thread.
public static func synthesizeText(_ text: String,
                                  config: TTSConfig = .default,
                              completion: ((
                                  _ taskId: String?,
                                  _ success: Bool,
                                  _ response: TTSResultModel?,
                                  _ error: NSError?
                              ) -> Void)? = nil) -> Void

请参阅 synthesizeText

配置与结果

TTSConfig 提供可选的 speakerId。值为 nil 时,服务商选择默认音色。

成功时,TTSResultModel 提供:

属性描述
audioFile相对于 App Documents 目录的音频文件路径。
audioFilePath合成音频文件的完整路径。
audioFormat合成音频文件的格式。

使用示例

Swift
let config = TTSConfig.default
config.speakerId = nil

DispatchQueue.global(qos: .userInitiated).async {
    AIBudsAISDK.synthesizeText(
        "Hello, how can I help you?",
        config: config
    ) { taskId, success, response, error in
        guard success, let response else {
            print(error?.localizedDescription ?? "Synthesis failed")
            return
        }

        print("Task: \(taskId ?? "Unavailable")")
        print("Audio: \(response.audioFilePath)")

        DispatchQueue.main.async {
            playAudio(atPath: response.audioFilePath)
        }
    }
}

注意事项

  • 此 API 生成文件,不会启动设备播放,也不提供 stopSpeaking()isSpeaking()
  • 应结合 successresponseerror 判断结果。操作成功要求 success == true 且 response 非 nil
  • 音色标识符由服务商定义,仅设置所选服务商文档中提供的标识符。
  • 将 UI 和音频播放器更新切回主线程。