Feel Physics Backyard

HoloLensの出張授業をする会社で、教材を開発しています

Swift Playgroundsに貼り付けるだけで確かめるAVFoundation(iOS9)

f:id:weed_7777:20160929140033j:plain

AVFoundationの勉強で、テキストの読み上げをさせてみました。以下のコードをSwift Playgroundに貼り付けるだけで動きます。ちなみにiPadのSwift Playgroundsに貼り付けても動きません。どうも文読み上げの辞書がアプリに入っていないようです。

//: Playground - noun: a place where people can play

import XCPlayground
XCPSetExecutionShouldContinueIndefinitely(true)

import AVFoundation

class THSpeechController{
    var synthesizer: AVSpeechSynthesizer
    var voices: [AVSpeechSynthesisVoice]
    var speechStrings: [String]
    
    init () {
        self.synthesizer = AVSpeechSynthesizer()
        self.voices = [
            AVSpeechSynthesisVoice(language: "en-US")!,
            AVSpeechSynthesisVoice(language: "en-GB")!]

        func buildSpeechStrings() -> [String] {
            return ["Hello AV Foundation. How are you?",
                    "I'm well! Thanks for asking."]
        }
        
        self.speechStrings = buildSpeechStrings()
    }
    
    func beginConversation() -> Void {
        let num = self.speechStrings.count
        for i in 0..<num {
            let utterance   = AVSpeechUtterance(string: speechStrings[i])
            utterance.voice = self.voices[i % 2]
            utterance.rate               = 0.4
            utterance.pitchMultiplier    = 0.8
            utterance.postUtteranceDelay = 0.1
            self.synthesizer.speakUtterance(utterance)
        }
    }
}

let sc = THSpeechController()
sc.beginConversation()