Fix infinite recursion on hiding panel when created during fullscreen mode.
[chromium-blink-merge.git] / chrome / browser / resources / app_list / audio_manager.js
blob9862ac431247eb1987f4b28c763fd982bd4b3ffb
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.
5 /**
6 * @fileoverview The manager of audio streams.
7 */
9 cr.define('speech', function() {
10 'use strict';
12 /**
13 * The enum of the status of hotword audio recognition.
15 * @enum {number}
17 var AudioState = {
18 STOPPED: 0,
19 LISTENING: 1
22 /**
23 * @constructor
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;
34 /**
35 * Called when the audio data arrives.
37 * @param {Event} audioEvent The audio event.
38 * @private
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');
46 event.data = intData;
47 this.dispatchEvent(event);
50 /**
51 * Called when the audio stream is ready.
53 * @param {MediaStream} stream The media stream which is now available.
54 * @private
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;
67 /**
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;
75 /**
76 * Starts the audio processing.
78 AudioManager.prototype.start = function() {
79 if (this.state == AudioState.LISTENING)
80 return;
82 if (this.audioProc_) {
83 this.audioProc_.connect(this.audioContext_.destination);
84 this.state = AudioState.LISTENING;
85 return;
88 navigator.webkitGetUserMedia(
89 {audio: true},
90 this.onAudioReady_.bind(this),
91 function(msg) { console.error('Failed to getUserMedia: ' + msg); });
94 /**
95 * Stops the audio processing.
97 AudioManager.prototype.stop = function() {
98 if (this.state != AudioState.LISTENING)
99 return;
100 this.audioProc_.disconnect();
101 this.state = AudioState.STOPPED;
104 return {
105 AudioManager: AudioManager,
106 AudioState: AudioState