简体   繁体   中英

getting text to speech to read items from an array

I now have threads working so I can start reading part of the array and use a button to stop it. The problem is that I cannot restart the reading. Any thoughts? Many thanks for people that helped previously.

import UIKit
import AVFoundation
var jj = 1
var writeString = "English Key Words#Alliteration - first sound in the word the same - ask Andrew#Rhyme - words end in the same sound - Black Jack#Rhythm – beat, regularity – di-da-di-da-di-da#Syllable – sound parts of a word – Happily – 3 syllables#Simile – like – the rain was like a drum on the roof#Metaphor – no ‘like’ – the rain was a drum on the roof#"
var noteArray = writeString.components(separatedBy: "#")

class ViewController: UIViewController {
    @IBAction func stop(_ sender: UIButton) {
        jj=0
        print(jj)
    }

    @IBAction func startIt(_ sender: UIButton) {
        DispatchQueue.global(qos: .userInteractive).async{
            while jj == 1 {
                for i in 27...29{
                    let string = noteArray[i]
                    let utterance = AVSpeechUtterance(string: string)
                    utterance.voice = AVSpeechSynthesisVoice(language: "en-GB")

                    let synthesizer = AVSpeechSynthesizer()
                    synthesizer.speak(utterance)
                    sleep(1)
            }
            sleep(5)
        }
        }
    }

   override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

The issue here is that you have not implemented the AVSpeechSynthesizerDelegate .

You can use this to determine when one utterance has been completed and then play another one.

As such here is a full working example for you:

import UIKit
import AVFoundation

extension ViewController: AVSpeechSynthesizerDelegate{

func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish      utterance: AVSpeechUtterance) {

    audioIndex += 1

    if audioIndex != noteArray.count{
        playWord(noteArray[audioIndex])
     } 
   }
 }

class ViewController: UIViewController {

//1. Create A Speech Utterance To Read Our Words
var wordReader: AVSpeechUtterance!

//2. Create The Speech Synthesizer
let speechSynthesizer = AVSpeechSynthesizer()

//3. Create The Names To Be Read
var noteArray = ["James","John","Jack","Jarred"]

//4. Store Out Current Audio File
var audioIndex = 0


override func viewDidLoad() {
    super.viewDidLoad()

    //1. Assign The SpeechSynteziser Delegate
    speechSynthesizer.delegate = self

    //2. Play The 1st Word
    playWord(noteArray[audioIndex])

}


/// Reads The Word
///
/// - Parameter word: String
func playWord(_ word: String){

        //3. Read The Word
        wordReader = AVSpeechUtterance(string: word)
        wordReader.rate = 0.5

        wordReader.volume = 1
        speechSynthesizer.speak(wordReader)

  }
}

Update:

Assuming I have interpreted your updated question this should get you started:

   import UIKit
   import AVFoundation

   //----------------
   //MARK: Delegation
   //----------------

   extension ViewController: AVSpeechSynthesizerDelegate{

  func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish      utterance: AVSpeechUtterance) {

    //1. Increase The Audio Index
    audioIndex += 1

    //2. Only Play The Next Utterance If It Is In Range
    if audioIndex != noteArray.count{

        //3. Play After A Delay Of 1 Secong
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
             self.playWordAtIndex(self.audioIndex)
        }

      }
   }
 }

class ViewController: UIViewController {

//1. Create A Speech Utterance To Read Our Words
var wordReader: AVSpeechUtterance!

//2. Create The Speech Synthesizer
let speechSynthesizer = AVSpeechSynthesizer()

//3. Create The Names To Be Read
let writeString = "English Key Words#Alliteration - first sound in the word the same - ask Andrew#Rhyme - words end in the same sound - Black Jack#Rhythm – beat, regularity – di-da-di-da-di-da#Syllable – sound parts of a word – Happily – 3 syllables#Simile – like – the rain was like a drum on the roof#Metaphor – no ‘like’ – the rain was a drum on the roof#"

//4. Create An Array To Store These
var noteArray = [String]()

//4. Store Out Current Audio File
var audioIndex = 0


//-------------------
//MARK: View Lifecyle
//-------------------

override func viewDidLoad() {
    super.viewDidLoad()

    //1. Create The Notes Array From The Necessary Components
    noteArray = writeString.components(separatedBy: "#")

    //2. Assign The SpeechSynteziser Delegate
    speechSynthesizer.delegate = self


}

func playWordAtIndex(_ index: Int){

    //1. Read The Word At The Current Audio Index
    wordReader = AVSpeechUtterance(string: noteArray[index])
    wordReader.rate = 0.5
    wordReader.volume = 1
    speechSynthesizer.speak(wordReader)
}

//----------------------
//MARK: User Interaction
//----------------------


 /// Begins The Audio Sequence
 ///
 /// - Parameter sender: UIButton
 @IBAction func startIt(_ sender: UIButton) {

    //If We Are Still In Range Play The Next Utterance
    if audioIndex != noteArray.count{

        playWordAtIndex(audioIndex)
    }
 }


/// Stops The Audio & Resets The Variable
///
/// - Parameter sender: UIButton
@IBAction func stop(_ sender: UIButton) {

    //1. Reset The Audio Index Count
    audioIndex = 0
    speechSynthesizer.stopSpeaking(at: AVSpeechBoundary.immediate)
   }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM