AVSpeechUtterance: как извлечь случайный массив и использовать определенный голос? - PullRequest
2 голосов
/ 24 мая 2019

Работая над использованием Swift для выдачи цитат, я сталкиваюсь с проблемами при повторении той же команды.

Вот что у меня сейчас

import AVFoundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let QuoteArray = [
"Quote1",
"Quote2",
"Quote3",
]

let max = QuoteArray.count

let synthesizer = AVSpeechSynthesizer()
let utterance = AVSpeechUtterance(string: QuoteArray[Int.random(in: 0 ... max)])
utterance.rate = 0.5
utterance.voice = AVSpeechSynthesisVoice(language: "en-AU")
synthesizer.speak(AVSpeechUtterance(string: QuoteArray[Int.random(in: 0 ... max)]))
sleep(5)
synthesizer.speak(AVSpeechUtterance(string: QuoteArray[Int.random(in: 0 ... max)]))
sleep(10)
synthesizer.speak(AVSpeechUtterance(string: QuoteArray[Int.random(in: 0 ... max)]))

Я не уверен, как выбрать случайную позицию массива и дурачиться с голосом синтеза и скоростью. Я пытаюсь сделать так, чтобы 3 случайные кавычки читались случайным образом, но я не могу заставить его работать должным образом.

Если я изменю последние несколько строк, чтобы вместо AVSpeechUtterance(string... они сказали utterance, я не смогу выполнить 2-ю или 3-ю кавычку из-за ошибки SIGBART.

Есть идеи?

utterance.rate = 35
utterance.pitchMultiplier = 3
utterance.voice = AVSpeechSynthesisVoice(language: "en-AU")
synth.speak(utterance)
sleep(5)
synth.speak(utterance)
sleep(10)
synth.speak(utterance)
sleep(15)

если я попытаюсь вернуть его к этим высказываниям, я получу

error: Execution was interrupted, reason: signal SIGABRT.
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation."

enter image description here

1 Ответ

1 голос
/ 25 мая 2019

Я не уверен, как выбрать случайную позицию массива ...

Ниже приведено решение вашей проблемы (swift 5.0, iOS 12) протестировано на игровом бланке проекта:

    import AVFoundation
    import UIKit

    let synthesizer = AVSpeechSynthesizer()
    let QuoteArray = ["Quote1",
                      "Quote2",
                      "Quote3"]

    func newRandomUtterance() -> AVSpeechUtterance {

        let utterance = AVSpeechUtterance(string: QuoteArray[Int.random(in: 0..<QuoteArray.count)])
        utterance.rate = AVSpeechUtteranceDefaultSpeechRate
        utterance.voice = AVSpeechSynthesisVoice(language: "en-GB")

        return utterance
     }

    for _ in 1...3 { synthesizer.speak(newRandomUtterance()) }

... и дурачиться с голосом синтеза и скоростью.

Есть подробное резюме видео WWDC 2018, посвященного синтезатору речи, и полное объяснение с фрагментами кода (ObjC и Swift) , которые могут помочь, если приведенного выше примера недостаточно.

Теперь вы сможете получить случайный массив и использовать определенный голос .

...