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 var audioContext
= new window
.AudioContext();
28 this.sampleRate
= audioContext
.sampleRate
;
29 this.audioProc_
= null;
32 this.state
= AudioState
.STOPPED
;
35 AudioManager
.prototype.__proto__
= cr
.EventTarget
.prototype;
38 * Called when the audio data arrives.
40 * @param {Event} audioEvent The audio event.
43 AudioManager
.prototype.onAudioProcess_ = function(audioEvent
) {
44 var data
= audioEvent
.inputBuffer
.getChannelData(0);
45 var intData
= new Int16Array(data
.length
);
46 for (var i
= 0; i
< data
.length
; ++i
)
47 intData
[i
] = Math
.round(data
[i
] * 32767);
48 var event
= new Event('audio');
50 this.dispatchEvent(event
);
54 * Called when the audio stream is ready.
56 * @param {MediaStream} stream The media stream which is now available.
59 AudioManager
.prototype.onAudioReady_ = function(stream
) {
60 var audioContext
= new window
.AudioContext();
61 this.stream_
= stream
;
62 this.audioIn_
= audioContext
.createMediaStreamSource(stream
);
63 this.audioProc_
= audioContext
.createScriptProcessor(
64 4096 /* buffer size */, 1 /* channels */, 1 /* channels */);
65 this.audioProc_
.onaudioprocess
= this.onAudioProcess_
.bind(this);
67 this.audioIn_
.connect(this.audioProc_
);
68 this.audioProc_
.connect(audioContext
.destination
);
69 this.state
= AudioState
.LISTENING
;
73 * Starts the audio processing.
75 AudioManager
.prototype.start = function() {
76 if (this.state
== AudioState
.LISTENING
)
79 navigator
.webkitGetUserMedia(
81 this.onAudioReady_
.bind(this),
82 function(msg
) { console
.error('Failed to getUserMedia: ' + msg
); });
86 * Stops the audio processing.
88 AudioManager
.prototype.stop = function() {
89 if (this.state
!= AudioState
.LISTENING
)
91 this.audioProc_
.disconnect();
92 this.audioIn_
.disconnect();
93 var audioTracks
= this.stream_
.getAudioTracks();
94 for (var i
= 0; i
< audioTracks
.length
; ++i
) {
95 audioTracks
[i
].stop();
97 this.audioProc_
= null;
100 this.state
= AudioState
.STOPPED
;
104 AudioManager
: AudioManager
,
105 AudioState
: AudioState