1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
6 * @fileoverview The manager of audio streams.
9 cr
.define('speech', function() {
13 * The enum of the status of hotword audio recognition.
24 * @extends {cr.EventTarget}
26 function AudioManager() {
27 this.audioContext_
= new window
.webkitAudioContext();
28 this.audioProc_
= null;
29 this.state
= AudioState
.STOPPED
;
32 AudioManager
.prototype.__proto__
= cr
.EventTarget
.prototype;
35 * Called when the audio data arrives.
37 * @param {Event} audioEvent The audio event.
40 AudioManager
.prototype.onAudioProcess_ = function(audioEvent
) {
41 var data
= audioEvent
.inputBuffer
.getChannelData(0);
42 var intData
= new Int16Array(data
.length
);
43 for (var i
= 0; i
< data
.length
; ++i
)
44 intData
[i
] = Math
.round(data
[i
] * 32767);
45 var event
= new Event('audio');
47 this.dispatchEvent(event
);
51 * Called when the audio stream is ready.
53 * @param {MediaStream} stream The media stream which is now available.
56 AudioManager
.prototype.onAudioReady_ = function(stream
) {
57 var audioIn
= this.audioContext_
.createMediaStreamSource(stream
);
58 this.audioProc_
= this.audioContext_
.createScriptProcessor(
59 4096 /* buffer size */, 1 /* channels */, 1 /* channels */);
60 this.audioProc_
.onaudioprocess
= this.onAudioProcess_
.bind(this);
62 audioIn
.connect(this.audioProc_
);
63 this.audioProc_
.connect(this.audioContext_
.destination
);
64 this.state
= AudioState
.LISTENING
;
68 * Returns the sampling rate of the current audio context.
69 * @return {number} The sampling rate.
71 AudioManager
.prototype.getSampleRate = function() {
72 return this.audioContext_
.sampleRate
;
76 * Starts the audio processing.
78 AudioManager
.prototype.start = function() {
79 if (this.state
== AudioState
.LISTENING
)
82 if (this.audioProc_
) {
83 this.audioProc_
.connect(this.audioContext_
.destination
);
84 this.state
= AudioState
.LISTENING
;
88 navigator
.webkitGetUserMedia(
90 this.onAudioReady_
.bind(this),
91 function(msg
) { console
.error('Failed to getUserMedia: ' + msg
); });
95 * Stops the audio processing.
97 AudioManager
.prototype.stop = function() {
98 if (this.state
!= AudioState
.LISTENING
)
100 this.audioProc_
.disconnect();
101 this.state
= AudioState
.STOPPED
;
105 AudioManager
: AudioManager
,
106 AudioState
: AudioState