Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / chrome / browser / resources / app_list / audio_manager.js
blobaa6beb0a2a39ab08df43909c49b5344208284255
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 var audioContext = new window.AudioContext();
28 this.sampleRate = audioContext.sampleRate;
29 this.audioProc_ = null;
30 this.audioIn_ = null;
31 this.stream_ = null;
32 this.state = AudioState.STOPPED;
35 AudioManager.prototype.__proto__ = cr.EventTarget.prototype;
37 /**
38 * Called when the audio data arrives.
40 * @param {Event} audioEvent The audio event.
41 * @private
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');
49 event.data = intData;
50 this.dispatchEvent(event);
53 /**
54 * Called when the audio stream is ready.
56 * @param {MediaStream} stream The media stream which is now available.
57 * @private
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;
72 /**
73 * Starts the audio processing.
75 AudioManager.prototype.start = function() {
76 if (this.state == AudioState.LISTENING)
77 return;
79 navigator.webkitGetUserMedia(
80 {audio: true},
81 this.onAudioReady_.bind(this),
82 function(msg) { console.error('Failed to getUserMedia: ' + msg); });
85 /**
86 * Stops the audio processing.
88 AudioManager.prototype.stop = function() {
89 if (this.state != AudioState.LISTENING)
90 return;
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;
98 this.audioIn_ = null;
99 this.stream_ = null;
100 this.state = AudioState.STOPPED;
103 return {
104 AudioManager: AudioManager,
105 AudioState: AudioState