Swift 实现iOS文字转语音

涉及到音视频的知识那肯定离不开 AVFoundation 框架啦。

所以实现的第一步那就是 import AVFoundation

实现语音读取文字,需要两个至关重要的类: 1.AVSpeechSynthesizer 语音合成器类 2.AVSpeechUtterance 语音表达设置类 这两个类都很简单,API 中的东西都很少。接下来实现一个小的功能,就是读取 textView 里输入的文字。 直接看实现的代码吧。

  let syntesizer = AVSpeechSynthesizer()
	var utterance = AVSpeechUtterance()
复制代码

播放

	@IBAction func play(_ sender: UIButton) {
		// 获取 textView 输入的文字
		let string = textView.text
		// 设置将要语音的文字
		utterance = AVSpeechUtterance(string: string!)
		// 语音的速度
		utterance.rate = 0.1
		// 开始朗读
		syntesizer.speak(utterance)
	}
复制代码

暂停

	@IBAction func pause(_ sender: UIButton) {
		// 暂停朗读
		syntesizer.pauseSpeaking(at: .immediate)
	}
复制代码

继续

	@IBAction func continuePlay(_ sender: UIButton) {
		// 继续朗读
		syntesizer.continueSpeaking()
	}
复制代码

停止

	@IBAction func stopPlay(_ sender: UIButton) {
		// 停止之后,继续是无法继续播放的,因为不是暂停
		syntesizer.stopSpeaking(at: .immediate)
	}
复制代码

代理

AVSpeechSynthesizer类有一个协议,实现他们可以做一些相应的处理。

extension ViewController: AVSpeechSynthesizerDelegate {
	
	func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) {
		print("开始")
	}
	
	func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
		 print("完成")
	}
	
	func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didPause utterance: AVSpeechUtterance) {
		 print("暂停")
	}
	
	func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didContinue utterance: AVSpeechUtterance) {
		 print("继续")
	}
	
	func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) {
		print("停止")
	}
	
	func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) {
		print("阅读过程中")
	}

}
复制代码

Demo 下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值