summaryrefslogtreecommitdiffstats
path: root/chrome/browser/extensions/extension_tts_api_win.cc
blob: 260d047908264d049cc38d942824e26832baf024 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "extension_tts_api.h"

#include <atlbase.h>
#include <atlcom.h>
#include <sapi.h>

#include "base/scoped_comptr_win.h"
#include "base/singleton.h"
#include "base/values.h"

class SpeechSynthesizerWrapper {
 public:
  SpeechSynthesizerWrapper() : speech_synthesizer_(NULL),
                               paused_(false),
                               permanent_failure_(false) {
    InitializeSpeechSynthesizer();
  }

  bool InitializeSpeechSynthesizer() {
    if (!SUCCEEDED(CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_SERVER,
        IID_ISpVoice, reinterpret_cast<void**>(&speech_synthesizer_)))) {
      permanent_failure_ = true;
      return false;
    }

    if (paused_)
      speech_synthesizer_->Resume();
    return true;
  }

  ScopedComPtr<ISpVoice> speech_synthesizer() {
    return speech_synthesizer_;
  }

  bool paused() {
    return paused_;
  }

  void paused(bool state) {
    paused_ = state;
  }

 private:
  ScopedComPtr<ISpVoice> speech_synthesizer_;
  bool paused_;
  // Indicates an error retrieving the SAPI COM interface.
  bool permanent_failure_;
};

typedef Singleton<SpeechSynthesizerWrapper> SpeechSynthesizerSingleton;

bool ExtensionTtsSpeakFunction::RunImpl() {
  ScopedComPtr<ISpVoice> speech_synthesizer =
      SpeechSynthesizerSingleton::get()->speech_synthesizer();
  if (speech_synthesizer) {
    std::wstring utterance;
    EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &utterance));
    if (SpeechSynthesizerSingleton::get()->paused())
      speech_synthesizer->Resume();
    speech_synthesizer->Speak(
        utterance.c_str(), SPF_ASYNC | SPF_PURGEBEFORESPEAK, NULL);
    return true;
  }

  return false;
}

bool ExtensionTtsStopSpeakingFunction::RunImpl() {
  // We need to keep track of the paused state since SAPI doesn't have a stop
  // method.
  ScopedComPtr<ISpVoice> speech_synthesizer =
      SpeechSynthesizerSingleton::get()->speech_synthesizer();
  if (speech_synthesizer && !SpeechSynthesizerSingleton::get()->paused()) {
    speech_synthesizer->Pause();
    SpeechSynthesizerSingleton::get()->paused(true);
  }
  return true;
}

bool ExtensionTtsIsSpeakingFunction::RunImpl() {
  return false;
}