首页 > 系统 > iOS > 正文

iOS10新特性之SFSpeechRecognizer的使用

2019-11-06 09:56:12
字体:
来源:转载
供稿:网友

SFSpeechRecognizer是iOS10新特性之一,用来进行语音识别的。

1、使用前需要导入头文件

import Speech

2、设置请求权限

//请求权限 SFSpeechRecognizer.requestAuthorization { (state) in PRint(state) }

3、配置info.plist

//添加一条权限Privacy - Speech Recognition Usage Description -> “xxx”

4、初始化识别器

//初始化一个识别器let recognizer = SFSpeechRecognizer(locale: Locale(identifier: "zh_CN"))

5、初始化请求

//path let url = Bundle.main.url(forResource: "bg", withExtension: "mp3") //初始化一个识别请求 let request = SFSpeechURLRecognitionRequest(url: url!)

6、开启识别任务

//开始一个识别请求recognizer?.recognitionTask(with: request, resultHandler: { (result, error) in if error != nil{ print("识别错误") return } else{ print(result?.bestTranscription.formattedString) } })

完成代码:

import UIKitimport Speechclass ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //请求权限 SFSpeechRecognizer.requestAuthorization { (state) in print(state) } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { //初始化一个识别器 let recognizer = SFSpeechRecognizer(locale: Locale(identifier: "zh_CN")) //path let url = Bundle.main.url(forResource: "bg", withExtension: "mp3") //初始化一个识别请求 let request = SFSpeechURLRecognitionRequest(url: url!) //开始一个识别请求 recognizer?.recognitionTask(with: request, resultHandler: { (result, error) in if error != nil{ print("识别错误") return } else{ print(result?.bestTranscription.formattedString) } }) }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表