SFSpeechRecognizer是iOS10新特性之一,用来进行语音识别的。
1、使用前需要导入头文件
import Speech2、设置请求权限
//请求权限 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) } }) }}新闻热点
疑难解答