├── arch.png ├── example_game.gif ├── frontend ├── firebase.json ├── firebase-rules.json └── public │ ├── third_party │ ├── jquery.voice.min.js │ ├── recorderWorker.js │ └── recorder.js │ ├── config.js │ ├── dpad.js │ ├── index.html │ ├── dpad.html │ └── script.js ├── backend ├── game-controller │ ├── package.json │ ├── config.js │ └── game-controller.js └── bigquery │ └── table-schema.json ├── CONTRIBUTING.md ├── README.md └── LICENSE /arch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googlesamples/Firebase-Plays-GCP-2016/HEAD/arch.png -------------------------------------------------------------------------------- /example_game.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googlesamples/Firebase-Plays-GCP-2016/HEAD/example_game.gif -------------------------------------------------------------------------------- /frontend/firebase.json: -------------------------------------------------------------------------------- 1 | { 2 | "public": "public", 3 | "rules": "firebase-rules.json", 4 | "ignore": [ 5 | "firebase.json", 6 | "**/.*", 7 | "**/node_modules/**" 8 | ] 9 | } -------------------------------------------------------------------------------- /frontend/firebase-rules.json: -------------------------------------------------------------------------------- 1 | { 2 | "rules": { 3 | "chat": { 4 | ".read": true, 5 | ".write": "auth != null" 6 | }, 7 | "commands-archive": { 8 | ".read": false, 9 | ".write": "auth != null" 10 | }, 11 | "commands": { 12 | ".read": "auth != null", 13 | ".write": true 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /backend/game-controller/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "game-control", 3 | "version": "1.0.0", 4 | "description": "Game controller to relay keystrokes", 5 | "main": "game-controller.js", 6 | "private": "true", 7 | "dependencies": { 8 | "@google-cloud/bigquery": "^0.11.1", 9 | "chance": "^1.0.3", 10 | "firebase-admin": "^5.5.1", 11 | "prompt": "^1.0.0", 12 | "robotjs": "^0.4.7", 13 | "sleep": "^3.0.1" 14 | }, 15 | "keywords": [ 16 | "game", 17 | "controller", 18 | "keystrokes" 19 | ], 20 | "author": "Google Inc.", 21 | "contributors": [ 22 | { 23 | "name": "Bret McGowen", 24 | "url": "https://twitter.com/bretmcg" 25 | } 26 | ], 27 | "license": "Apache-2.0" 28 | } 29 | -------------------------------------------------------------------------------- /backend/bigquery/table-schema.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "mode": "NULLABLE", 4 | "name": "command", 5 | "type": "STRING" 6 | }, 7 | { 8 | "mode": "NULLABLE", 9 | "name": "country", 10 | "type": "STRING" 11 | }, 12 | { 13 | "mode": "NULLABLE", 14 | "name": "city", 15 | "type": "STRING" 16 | }, 17 | { 18 | "mode": "NULLABLE", 19 | "name": "state", 20 | "type": "STRING" 21 | }, 22 | { 23 | "mode": "NULLABLE", 24 | "name": "timestamp", 25 | "type": "TIMESTAMP" 26 | }, 27 | { 28 | "mode": "NULLABLE", 29 | "name": "browser", 30 | "type": "STRING" 31 | }, 32 | { 33 | "mode": "NULLABLE", 34 | "name": "device", 35 | "type": "STRING" 36 | }, 37 | { 38 | "mode": "NULLABLE", 39 | "name": "os", 40 | "type": "STRING" 41 | } 42 | ] 43 | -------------------------------------------------------------------------------- /backend/game-controller/config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright 2016, Google, Inc. 4 | * Licensed under the Apache License, Version 2.0 (the 'License'); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an 'AS IS' BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 'use strict'; 18 | 19 | module.exports = { 20 | firebase: { 21 | apiKey: '', 22 | authDomain: '', 23 | databaseUrl: '', 24 | commandsQueueNode: 'commands', 25 | commandsArchiveNode: 'commands-archive', 26 | serviceAccountFilePath: './firebase-plays.json' 27 | }, 28 | projectId: '', 29 | dataset: 'firebase_plays', 30 | table: 'commands' 31 | }; 32 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Want to contribute? Great! First, read this page (including the small print at the end). 2 | 3 | ### Before you contribute 4 | Before we can use your code, you must sign the 5 | [Google Individual Contributor License Agreement] 6 | (https://cla.developers.google.com/about/google-individual) 7 | (CLA), which you can do online. The CLA is necessary mainly because you own the 8 | copyright to your changes, even after your contribution becomes part of our 9 | codebase, so we need your permission to use and distribute your code. We also 10 | need to be sure of various other things—for instance that you'll tell us if you 11 | know that your code infringes on other people's patents. You don't have to sign 12 | the CLA until after you've submitted your code for review and a member has 13 | approved it, but you must do it before we can put your code into our codebase. 14 | Before you start working on a larger contribution, you should get in touch with 15 | us first through the issue tracker with your idea so that we can help out and 16 | possibly guide you. Coordinating up front makes it much easier to avoid 17 | frustration later on. 18 | 19 | ### Code reviews 20 | All submissions, including submissions by project members, require review. We 21 | use Github pull requests for this purpose. 22 | 23 | ### The small print 24 | Contributions made by corporations are covered by a different agreement than 25 | the one above, the 26 | [Software Grant and Corporate Contributor License Agreement] 27 | (https://cla.developers.google.com/about/google-corporate). -------------------------------------------------------------------------------- /frontend/public/third_party/jquery.voice.min.js: -------------------------------------------------------------------------------- 1 | /** 2 | * jQuery Voice plugin 0.3 (31st May 2015) 3 | * Copyright Subin Siby - http://subinsb.com 4 | * 5 | * ------------------ 6 | * Licensed under MIT 7 | * ------------------ 8 | * 9 | * A jQuery plugin to record, play & download microphone input sound from the user. 10 | * NEEDS recorder.js and recorderWorker.js to work - https://github.com/mattdiamond/Recorderjs 11 | * 12 | * To use MP3 conversion, NEEDS mp3Worker.js, libmp3lame.min.js and recorder.js from https://github.com/nusofthq/Recordmp3js/tree/master/js 13 | * 14 | * Full Documentation & Support - http://subinsb.com/html5-record-mic-voice 15 | */ 16 | window.Fr=window.Fr||{},function(){Fr.voice={workerPath:"third_party/recorderWorker.js",mp3WorkerPath:"third_party/mp3Worker.js",stream:!1,init_called:!1,init:function(){try{window.AudioContext=window.AudioContext||window.webkitAudioContext,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,window.URL=window.URL||window.webkitURL,navigator.getUserMedia===!1&&alert("getUserMedia() is not supported in your browser"),this.context=new AudioContext}catch(t){alert("Web Audio API is not supported in this browser")}},record:function(t,e){this.init_called===!1&&(this.init(),this.init_called=!0),$that=this,navigator.getUserMedia({audio:!0},function(r){var i=$that.context.createMediaStreamSource(r);t===!0&&i.connect($that.context.destination),$that.recorder=new Recorder(i,{workerPath:$that.workerPath,mp3WorkerPath:$that.mp3WorkerPath}),$that.stream=r,$that.recorder.record(),e(r)},function(){alert("No live audio input")})},stop:function(){return this.recorder.stop(),this.recorder.clear(),this.stream.stop(),this},"export":function(t,e){"mp3"==e?this.recorder.exportMP3(t):this.recorder.exportWAV(function(r){if(""==e||"blob"==e)t(r);else if("base64"==e){var i=new window.FileReader;i.readAsDataURL(r),i.onloadend=function(){base64data=i.result,t(base64data)}}else if("URL"==e){var o=URL.createObjectURL(r);t(o)}})}}}(jQuery); 17 | -------------------------------------------------------------------------------- /frontend/public/third_party/recorderWorker.js: -------------------------------------------------------------------------------- 1 | /* 2 | The MIT License (MIT) 3 | 4 | Copyright (c) 2014 nusofthq 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | 8 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | 10 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | */ 12 | function init(e){sampleRate=e.sampleRate}function record(e){recBuffersL.push(e[0]),recLength+=e[0].length}function exportWAV(e){var t=mergeBuffers(recBuffersL,recLength),r=encodeWAV(t),n=new Blob([r],{type:e});this.postMessage(n)}function getBuffer(){var e=[];e.push(mergeBuffers(recBuffersL,recLength)),e.push(mergeBuffers(recBuffersR,recLength)),this.postMessage(e)}function clear(){recLength=0,recBuffersL=[],recBuffersR=[]}function mergeBuffers(e,t){for(var r=new Float32Array(t),n=0,a=0;aa;)n[a++]=e[f],n[a++]=t[f],f++;return n}function floatTo16BitPCM(e,t,r){for(var n=0;na?32768*a:32767*a,!0)}}function writeString(e,t,r){for(var n=0;n=0x8000)value|=~0x7FFF;f32Buffer[i]=value/0x8000;} 22 | return f32Buffer;} 23 | function encode64(buffer){var binary='',bytes=new Uint8Array(buffer),len=bytes.byteLength;for(var i=0;i 0) { 117 | var arrow = arrows.shift(); 118 | document.getElementById(arrow).style.display = 'block'; 119 | $('#command-list').prepend(''); 120 | } 121 | } 122 | 123 | // Every 200ms, check the arrow queue for commands to display 124 | setInterval(displayArrows, 200); 125 | 126 | // Show commands from all users playing the game 127 | commands.on('child_added', function(snap) { 128 | var arrow = snap.val().command; 129 | $('#all-command-list').prepend(''); 130 | }); 131 | -------------------------------------------------------------------------------- /frontend/public/index.html: -------------------------------------------------------------------------------- 1 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | Firebase Plays with Google Cloud 25 | 26 | 27 | 28 | 42 | 43 | 44 |
45 |
46 |
47 |
48 |
49 |
50 | 57 | 64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 | 72 |    73 | 74 |
75 |
76 |
77 |
78 |
79 | 80 |
81 |
82 |
83 |
84 | Chat 85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /frontend/public/dpad.html: -------------------------------------------------------------------------------- 1 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | Firebase + Google Cloud Platform 22 | 23 | 24 | 25 | 26 | 55 | 56 | 57 |
58 |
59 |
60 |

Firebase Google Cloud Platform

61 |
62 |
63 |
64 |
65 |
66 |
67 | 74 | Your browser doesn't support audio capture. 75 |
76 |
77 |
78 |
79 | 82 |
83 | 86 | 89 |
90 | 93 |
94 |
95 |
96 |
97 |
98 |
99 |

Speech API Output

100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |

Your Commands

114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |

All Commands

128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This is not an official Google product. 2 | 3 | # Crowdsourced Realtime Gaming 4 | 5 | We decided to get a little crazy and build a real time, crowdsourced, and live streamed gaming platform. 6 | 7 | Imagine players all over the world shouting "up! down! left! right!" into their computers and phones to control a common character while chatting in different languages. 8 | 9 | Inspired by [Twitch Plays Pokémon](https://en.wikipedia.org/wiki/Twitch_Plays_Pok%C3%A9mon), this game uses [Firebase](https://firebase.google.com) to crowdsource input from thousands of players in real time, then a Node.js process running on a [Google Compute Engine](https://cloud.google.com/compute/) Windows VM sends these crowdsourced commands to a game, and live streams it all to YouTube. 10 | 11 | ![Realtime Game Example](example_game.gif) 12 | 13 | The game's web front end uses the power of [Google Cloud Machine Learning](https://cloud.google.com/products/machine-learning/) to enable realtime voice transcription and translation. 14 | 15 | Finally, [BigQuery](https://cloud.google.com/bigquery/) gives us the power of big data to analyse all the commands and find interesting patterns. 16 | 17 | ![Architecture](arch.png) 18 | 19 | This is originally presented at Google I/O 2016. You can watch the talk here: 20 | 21 | ![YouTube Video](http://img.youtube.com/vi/wOGfZ_aLGqM/maxresdefault.jpg) 22 | 23 | # Setup 24 | 25 | There are three components of this demo that run in the cloud: 26 | - **Firebase** handles all of the real-time data syncing between multiple players and the game server. Firebase will handle relaying commands from every player to the server, as well as syncing chat messages between players. 27 | - **The game server** is a Windows virtual machine running on [Google Compute Engine](https://cloud.google.com/compute/). It runs the game natively, relays user commands to the game, and streams everything to YouTube Live. 28 | - **BigQuery** is the cloud data analytics platform that will receive all game events, and supports using SQL to query various reports. 29 | 30 | ## Set up your Firebase and Google Cloud Platform project 31 | 32 | 1. Create a new [Firebase project](https://firebase.google.com). 33 | 2. Click **Add Firebase to your web app** to get the Firebase and Google Cloud Platform connection settings: 34 | - API key 35 | - Database URL 36 | - Project ID. 37 | 38 | Follow the instructions [here](https://firebase.google.com/docs/web/setup) to extract your project ID. 39 | 40 | The settings should look something like: 41 | ```js 42 | var config = { 43 | apiKey: '...', 44 | databaseURL: '...', 45 | projectId: '...' 46 | }; 47 | ``` 48 | Replace the placeholders in [frontend/public/config.js](frontend/public/config.js) with these values. 49 | 50 | ### Firebase security settings 51 | We require users to be authenticated to write messages to the chat node or read from the 52 | commands queue. These rules will be automatically deployed as they are included in the [firebase.json](frontend/firebase.json) file. 53 | ```json 54 | { 55 | "rules": { 56 | "chat": { 57 | ".read": true, 58 | ".write": "auth != null" 59 | }, 60 | "commands-archive": { 61 | ".read": false, 62 | ".write": "auth != null" 63 | }, 64 | "commands": { 65 | ".read": "auth != null", 66 | ".write": true 67 | } 68 | } 69 | } 70 | ``` 71 | 72 | ### Firebase service account 73 | Create a service account that you'll upload to your game server created in the 74 | next step. 75 | 1. [Create a service account](https://console.firebase.google.com/iam-admin/serviceaccounts) 76 | for your Firebase project. 77 | 2. Select **Furnish a new private key** and select type JSON. Rename this file 78 | to ```firebase-plays.json```. Save this file; you'll upload it to your game 79 | server in the next section. 80 | 81 | ## Enable Speech and Translate APIs 82 | 83 | - [Click here](https://console.cloud.google.com/apis/library/speech.googleapis.com) to make sure the Cloud Speech API is enabled for your project. 84 | - [Click here](https://console.cloud.google.com/apis/api/translate/overview) to make sure the Cloud Translate API is enabled for your project. 85 | 86 | ## Create the game server 87 | [Create a Windows virtual machine](https://console.cloud.google.com/launcher/details/windows-cloud/windows-server-2016?q=windows%20server%202016) using the Cloud Launcher. Click **Launch on Compute Engine** and then click **Create** on the next page. 88 | 89 | Install the following on the Windows virtual machine: 90 | - [Google Chrome](https://www.google.com/chrome/browser) 91 | - [gcloud](https://cloud.google.com/sdk/downloads#windows) - the Cloud SDK for Google Cloud Platform. Should already be preinstalled on your Windows virtual machine. 92 | - [Node.js](https://nodejs.org/en/download/) 93 | - [Python](https://www.python.org/downloads/windows/) (and add to PATH) 94 | - As administrator run ```npm install --global --production windows-build-tools``` and then ```npm config set msvs_version 2015 --global``` to address [this MSBUILD issue](https://github.com/chjj/pty.js/issues/60). 95 | - [Install git](https://git-scm.com/download/win) 96 | 97 | ### Optional: YouTube live streaming 98 | 1. Set up [YouTube live streaming](https://support.google.com/youtube/answer/2474026?hl=en) on your YouTube channel, and install an encoder on your [Windows virtual machine](https://support.google.com/youtube/answer/2907883). 99 | 1. Get your YouTube live stream channel URL and paste it into [frontend/index.html](frontend/index.html). 100 | 101 | ## Set up BigQuery 102 | 1. [Go to the BigQuery page](https://bigquery.cloud.google.com) for your project. 103 | 1. Create a **new dataset** named ```firebase_plays```. 104 | 2. Create a **new table** named ```commands```. Choose **Empty Data source**, and then under schema, click **Edit as Text** and paste in the contents of the [table-schema.json](backend/bigquery/table-schema.json) file. 105 | 106 | ## Deploy the web app 107 | 108 | Make sure you have the [Firebase SDK](https://firebase.google.com/docs/cli/) installed. You can install it with this command: 109 | 110 | `npm install -g firebase-tools` 111 | 112 | To deploy, run the following command in the `frontend` folder: 113 | 114 | `firebase deploy --project ` 115 | 116 | ## Run the game and Node.js game-controller app 117 | 1. Install and run whatever game you'd like to run on your game server. The script only supports the arrow keys on the keyboard by default. 118 | 1. On the Windows game server, run the following commands in the **git bash** terminal: 119 | 1. ```git clone https://github.com/googlesamples/Firebase-Plays-GCP-2016``` 120 | 1. ```cd backend/game-controller``` 121 | 1. Copy the Firebase service account ```firebase-plays.json``` that you created in a previous step to ```backend/game-controller``` on the Windows game server. 122 | 1. Edit ```config.js``` to include the API key, Project ID, Auth Domain, and Database URL values from your Firebase project. 123 | 1. ```npm install``` 124 | 1. ```node game-controller.js``` 125 | 3. Click the running game to ensure it has focus so game-controller.js can relay keystrokes into the game. 126 | 127 | ### Sample BigQuery queries: 128 | 129 | #### Most common game commands 130 | ```sql 131 | SELECT command, count(command) FROM [social_gaming.game_commands] GROUP BY command 132 | ``` 133 | 134 | #### Commands by city 135 | ```sql 136 | SELECT city, count(*) AS count FROM [social_gaming.game_commands] GROUP BY city 137 | ``` 138 | 139 | #### Commands by time of day 140 | ```sql 141 | SELECT 142 | STRFTIME_UTC_USEC([timestamp], '%I %p') AS hour, count(*) AS count 143 | FROM 144 | [social_gaming.game_commands] 145 | GROUP BY 146 | hour 147 | ``` 148 | -------------------------------------------------------------------------------- /frontend/public/script.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright 2016, Google, Inc. 4 | * Licensed under the Apache License, Version 2.0 (the 'License'); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an 'AS IS' BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // Firebase User Auth 18 | function signIn(googleUser) { 19 | var credential = firebase.auth.GoogleAuthProvider.credential({ 20 | 'idToken' : googleUser.getAuthResponse().id_token 21 | }); 22 | auth.signInWithCredential(credential).then(function(user) { 23 | console.log('Sign In Success', user); 24 | userName = user.displayName; 25 | document.getElementById('btn').className = 'btn btn-success btn-raised'; 26 | document.getElementById('signOut').className = 'btn btn-default btn-raised'; 27 | document.getElementById('signIn').className = 'g-signin2 hidden'; 28 | document.getElementById('interm').textContent = 'Click "Start" and say some commands: Up, Down, Left, Right. Talk for chat!'; 29 | }, function(error) { 30 | console.error('Sign In Error', error); 31 | }); 32 | } 33 | 34 | function signOut() { 35 | var auth2 = gapi.auth2.getAuthInstance(); 36 | auth2.signOut().then(function() { 37 | console.log('User signed out.'); 38 | document.getElementById('btn').className = 'btn btn-success btn-raised hidden'; 39 | document.getElementById('signOut').className = 'btn btn-default btn-raised hidden'; 40 | document.getElementById('signIn').className = 'g-signin2'; 41 | document.getElementById('interm').textContent = ''; 42 | }); 43 | } 44 | 45 | // Add Message to Chat Box 46 | chat.on('child_added', function(snap) { 47 | var userName = document.createElement('b'); 48 | var text = document.createElement('span'); 49 | var msg = document.createElement('div'); 50 | msg.className = 'well well-sm'; 51 | msg.style.cursor = 'pointer'; 52 | 53 | userName.textContent = snap.val().name + ': '; 54 | text.textContent = snap.val().text; 55 | 56 | msg.appendChild(userName); 57 | msg.appendChild(text); 58 | 59 | objDiv = document.getElementById('chat'); 60 | objDiv.insertBefore(msg, objDiv.firstChild); 61 | objDiv.scrollTop = 0; 62 | 63 | // Flip between original text and translated text on click 64 | var original = false; 65 | msg.addEventListener('click', function() { 66 | if (original) { 67 | translate(); 68 | text.style.color = 'black'; 69 | } else { 70 | text.textContent = snap.val().text; 71 | text.style.color = 'red'; 72 | } 73 | original = !original; 74 | }); 75 | 76 | // Call the Translate API 77 | function translate() { 78 | fetch('https://www.googleapis.com/language/translate/v2?key=' + 79 | config.apiKey + 80 | '&q=' + snap.val().text + 81 | '&target=' + select_dialect.value.substring(0, 2), 82 | { 83 | method: 'get' 84 | }).then(function(response) { 85 | return response.json(); 86 | }).then(function(response) { 87 | text.textContent = response.data.translations[0].translatedText; 88 | }); 89 | }; 90 | translate(); 91 | 92 | // Re-translate when language is changed 93 | window.addEventListener('country_change', function() { 94 | translate(); 95 | }); 96 | 97 | }); 98 | 99 | // Check if browser supports WebSpeech API 100 | if (!('webkitSpeechRecognition' in window)) { 101 | alert("Your browser doesn't support the Web Speech API :("); 102 | } else { 103 | var recognizing = false; 104 | var recognition = new webkitSpeechRecognition(); 105 | recognition.continuous = true; 106 | recognition.interimResults = false; 107 | 108 | function startListening(event) { 109 | if (recognizing) { 110 | document.getElementById('select_language').disabled = false; 111 | document.getElementById('select_dialect').disabled = false; 112 | recognition.stop(); 113 | }else { 114 | document.getElementById('select_language').disabled = true; 115 | document.getElementById('select_dialect').disabled = true; 116 | recognition.lang = select_dialect.value; 117 | recognition.start(); 118 | } 119 | } 120 | 121 | // Create Stop Button once WebSpeech API starts 122 | recognition.onstart = function() { 123 | recognizing = true; 124 | document.getElementById('btnText').textContent = 'Stop'; 125 | document.getElementById('btn').className = 'btn btn-danger btn-raised'; 126 | }; 127 | 128 | // Create Start Button once WebSpeech API ends 129 | recognition.onend = function() { 130 | recognizing = false; 131 | document.getElementById('btnText').textContent = 'Start'; 132 | document.getElementById('btn').className = 'btn btn-success btn-raised'; 133 | }; 134 | 135 | // Display WebSpeech API errors 136 | recognition.onerror = function(event) { 137 | if (event.error == 'no-speech') { 138 | alert('No speech was detected'); 139 | } 140 | else if (event.error == 'audio-capture') { 141 | alert('Could not detect a microphone on your device'); 142 | } 143 | else if (event.error == 'not-allowed') { 144 | alert('Cannot access your microphone. Did you grant permissions?'); 145 | } 146 | else { 147 | alert('Unknown Error with Speech Recognition - ' + event.error); 148 | } 149 | }; 150 | 151 | // Handle WebSpeech API results 152 | recognition.onresult = function(event) { 153 | for (var i = event.resultIndex; i < event.results.length; ++i) { 154 | // Only parse text when we get the final results 155 | if (!(event.results[i].isFinal)) {return;} 156 | // Split text into individual words 157 | var text = event.results[i][0].transcript.split(' '); 158 | // Output to hold the comments 159 | var output = ''; 160 | var other = false; 161 | for (var j = 0; j < text.length; j++) { 162 | // If we find a command, send it to the command list in Firebase 163 | var lowerCommand = text[j].toLowerCase(); 164 | if (commandList.indexOf(lowerCommand) != -1) { 165 | userInfo.command = lowerCommand; 166 | arrows.push(lowerCommand); 167 | commands.push(userInfo); 168 | // Otherwise, add it to the chat 169 | } else if (text[j] != '') { 170 | other = true; 171 | } 172 | output += text[j] + ' '; 173 | } 174 | if (other) { 175 | // Push chat messages up once everything is compiled 176 | chat.push({name: userName, text: output}); 177 | } 178 | } 179 | }; 180 | 181 | // Flash directional arrows on the screen 182 | var arrows = []; 183 | function displayArrows() { 184 | for (var w = 0; w < commandList.length; w++) { 185 | document.getElementById(commandList[w]).style.display = 'none'; 186 | } 187 | if (arrows.length > 0) { 188 | document.getElementById(arrows.shift()).style.display = 'block'; 189 | } 190 | } 191 | setInterval(function() { displayArrows(); }, 200); 192 | 193 | } 194 | 195 | // Language Selector 196 | var langs = 197 | [['Afrikaans', 'af', ['af-ZA']], 198 | ['Bahasa Indonesia', 'id', ['id-ID']], 199 | ['Bahasa Melayu', 'ms', ['ms-MY']], 200 | ['Català', ['ca-ES']], 201 | ['Čeština', ['cs-CZ']], 202 | ['Deutsch', ['de-DE']], 203 | ['English', ['en-AU', 'Australia'], 204 | ['en-CA', 'Canada'], 205 | ['en-IN', 'India'], 206 | ['en-NZ', 'New Zealand'], 207 | ['en-ZA', 'South Africa'], 208 | ['en-GB', 'United Kingdom'], 209 | ['en-US', 'United States']], 210 | ['Español', ['es-AR', 'Argentina'], 211 | ['es-BO', 'Bolivia'], 212 | ['es-CL', 'Chile'], 213 | ['es-CO', 'Colombia'], 214 | ['es-CR', 'Costa Rica'], 215 | ['es-EC', 'Ecuador'], 216 | ['es-SV', 'El Salvador'], 217 | ['es-ES', 'España'], 218 | ['es-US', 'Estados Unidos'], 219 | ['es-GT', 'Guatemala'], 220 | ['es-HN', 'Honduras'], 221 | ['es-MX', 'México'], 222 | ['es-NI', 'Nicaragua'], 223 | ['es-PA', 'Panamá'], 224 | ['es-PY', 'Paraguay'], 225 | ['es-PE', 'Perú'], 226 | ['es-PR', 'Puerto Rico'], 227 | ['es-DO', 'República Dominicana'], 228 | ['es-UY', 'Uruguay'], 229 | ['es-VE', 'Venezuela']], 230 | ['Euskara', ['eu-ES']], 231 | ['Français', ['fr-FR']], 232 | ['Galego', ['gl-ES']], 233 | ['Hrvatski', ['hr_HR']], 234 | ['IsiZulu', ['zu-ZA']], 235 | ['Íslenska', ['is-IS']], 236 | ['Italiano', ['it-IT', 'Italia'], 237 | ['it-CH', 'Svizzera']], 238 | ['Magyar', ['hu-HU']], 239 | ['Nederlands', ['nl-NL']], 240 | ['Norsk bokmål', ['nb-NO']], 241 | ['Polski', ['pl-PL']], 242 | ['Português', ['pt-BR', 'Brasil'], 243 | ['pt-PT', 'Portugal']], 244 | ['Română', ['ro-RO']], 245 | ['Slovenčina', ['sk-SK']], 246 | ['Suomi', ['fi-FI']], 247 | ['Svenska', ['sv-SE']], 248 | ['Türkçe', ['tr-TR']], 249 | ['български', ['bg-BG']], 250 | ['Pусский', ['ru-RU']], 251 | ['Српски', ['sr-RS']], 252 | ['한국어', ['ko-KR']], 253 | ['中文', ['cmn-Hans-CN', '普通话 (中国大陆)'], 254 | ['cmn-Hans-HK', '普通话 (香港)'], 255 | ['cmn-Hant-TW', '中文 (台灣)'], 256 | ['yue-Hant-HK', '粵語 (香港)']], 257 | ['日本語', ['ja-JP']], 258 | ['Lingua latīna', ['la']], 259 | ['Hebrew', ['he-IL']]]; 260 | 261 | var country_change = new Event('country_change'); 262 | 263 | for (var i = 0; i < langs.length; i++) { 264 | select_language.options[i] = new Option(langs[i][0], i); 265 | } 266 | select_language.selectedIndex = 6; 267 | updateCountry(); 268 | select_dialect.selectedIndex = 6; 269 | 270 | function updateCountry() { 271 | for (var i = select_dialect.options.length - 1; i >= 0; i--) { 272 | select_dialect.remove(i); 273 | } 274 | var list = langs[select_language.selectedIndex]; 275 | for (var i = 1; i < list.length; i++) { 276 | select_dialect.options.add(new Option(list[i][1], list[i][0])); 277 | } 278 | select_dialect.style.visibility = list[1].length == 1 ? 'hidden' : 'visible'; 279 | window.dispatchEvent(country_change); 280 | } 281 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. --------------------------------------------------------------------------------