Skip to content

Instantly share code, notes, and snippets.

@ccjeng
Created November 3, 2016 05:41
Show Gist options
  • Save ccjeng/23479a79b9f9bd7da65324b404f97331 to your computer and use it in GitHub Desktop.
Save ccjeng/23479a79b9f9bd7da65324b404f97331 to your computer and use it in GitHub Desktop.
Swift TextToSpeech sample
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var txtFieldText: UITextField!
@IBOutlet weak var labelMessage: UILabel!
let synth = AVSpeechSynthesizer()
var myUtterance = AVSpeechUtterance(string: "")
@IBAction func textToSpeechButton(_ sender: UIButton) {
myUtterance = AVSpeechUtterance(string: txtFieldText.text!)
myUtterance.rate = 0.4
myUtterance.pitchMultiplier = 1.2
myUtterance.postUtteranceDelay = 0.1
myUtterance.volume = 1
myUtterance.voice = AVSpeechSynthesisVoice(language: "zh-TW")
synth.speak(myUtterance)
}
override func viewDidLoad() {
super.viewDidLoad()
//TTS is working for physical device after adding below code
do{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
do{
try AVAudioSession.sharedInstance().setActive(true)
}catch{
}
}catch{
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
@Ashish020794
Copy link

I am converting text to speech and playing it on the Car's bluetooth speaker. But when it plays on the car's bluetooth , the car's bluetooth screen show that it initiated the call on the self number. If the iPhone do not contains the SIM card it starts showing the timer. iPhone has no sign of calling being initiated.

I am using following code to play the text in car's bluetooth :

let audioSession = AVAudioSession.sharedInstance()
try? audioSession.setCategory(AVAudioSession.Category.playAndRecord, mode: AVAudioSession.Mode.default, options: [.defaultToSpeaker, .allowBluetooth,.allowBluetoothA2DP])
do {
try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
} catch {
print("Error in the session")
}

let utterance = AVSpeechUtterance(string: text)
utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
synth.speak(utterance)
synth.continueSpeaking()

I tried using only . allowBluetoothA2DP but audio cannot be heard in Bluetooth speaker when I am doing this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment