├── .github └── FUNDING.yml ├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src ├── main └── java │ └── com │ └── goxr3plus │ └── speech │ ├── microphone │ ├── Microphone.java │ └── MicrophoneAnalyzer.java │ ├── recognizer │ ├── FlacEncoder.java │ ├── GSpeechDuplex.java │ ├── GSpeechResponseListener.java │ ├── GoogleResponse.java │ ├── Languages.java │ ├── Recognizer.java │ └── RecognizerChunked.java │ ├── synthesiser │ ├── BaseSynthsiser.java │ ├── Synthesiser.java │ └── SynthesiserV2.java │ ├── translator │ └── GoogleTranslate.java │ └── util │ ├── ChunkedOutputStream.java │ ├── Complex.java │ ├── FFT.java │ └── StringUtil.java └── test └── java └── translator └── TranslatorTest.java /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: GOXR3PLUSTUDIO 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: goxr3plusstudio 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | custom: https://www.paypal.me/GOXR3PLUSCOMPANY 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.ear 17 | *.zip 18 | *.tar.gz 19 | *.rar 20 | 21 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 22 | hs_err_pid* 23 | 24 | 25 | #Maven Target Folder 26 | /target 27 | .classpath 28 | .project 29 | 30 | *.settings/ 31 | *.idea/ 32 | *.iml -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/Q5Q3WBIC) 2 | 3 | THIS LIBRARY IS NOT SUPPORTED BY ME ACTIVELY ANYMORE , feel free to contribute :) 4 | 5 | --- 6 | 7 |

Java Google Speech Api ( Library )

8 |

9 | 🎤 10 |

11 |

12 | 13 | This project is designed to be simple and efficient, using the speech engines created by Google to provide functionality for parts of the API. Essentially, it is an API written in Java, including a recognizer, synthesizer, and a microphone capture utility. The project uses Google services for the synthesizer and recognizer. While this requires an Internet connection, it provides a complete, modern, and fully functional speech API in Java. 14 | 15 |

16 | 17 | --- 18 | 19 | [![Latest Version](https://img.shields.io/github/release/goxr3plus/java-google-speech-api.svg?style=flat-square)](https://github.com/goxr3plus/java-google-speech-api/releases) 20 | [![GitHub contributors][contributors-image]][contributors-url] 21 | [![HitCount](http://hits.dwyl.io/goxr3plus/java-google-speech-api.svg)](http://hits.dwyl.io/goxr3plus/java-google-speech-api) 22 | [![Total Downloads](https://img.shields.io/github/downloads/goxr3plus/java-google-speech-api/total.svg)](https://github.com/goxr3plus/java-google-speech-api/releases) 23 | 24 | 25 | [contributors-url]: https://github.com/goxr3plus/java-google-speech-api/graphs/contributors 26 | [contributors-image]: https://img.shields.io/github/contributors/goxr3plus/java-google-speech-api.svg 27 | 28 | 29 | ## Google has released it's official library for [Google Speech Recognition](https://github.com/googleapis/java-speech) . Check this issue for Official Google Speech Library code solution -> [#4](https://github.com/goxr3plus/java-google-speech-api/issues/4) 30 | 31 | 32 | ### Add it to your project using JitPack : 33 | 34 | https://jitpack.io/private#goxr3plus/java-google-speech-api 35 | 36 | >Step 1. Add the JitPack repository to your build file 37 | ``` XML 38 | 39 | 40 | jitpack.io 41 | https://jitpack.io 42 | 43 | 44 | ``` 45 | 46 | >Step 2. Add the dependency 47 | ``` XML 48 | 49 | com.github.goxr3plus 50 | java-google-speech-api 51 | 8.0.0 52 | 53 | ``` 54 | 55 | 56 | # Java Google Speech API 57 | 58 | ##### Warning : The default secret key i was using is not working anymore (because ... i have to pay lol ) , you have to make your own , check tutorials :) 59 | 60 | ### Description 61 | This project is designed to be simple and efficient, using the speech engines created by Google to provide functionality for parts of the API. Essentially, it is an API written in Java, including a recognizer, synthesizer, and a microphone capture utility. The project uses Google services for the synthesizer and recognizer. While this requires an Internet connection, it provides a complete, modern, and fully functional speech API in Java. 62 | 63 | 64 | ### Features 65 | This project is separated on 3 parts : 66 | 67 | **1)** Google Speech Recognition based on Chromium Speech API (which is free with restrictions for commercial applications) through [GSpeechDuplex.java]( java-google-speech-api/src/main/java/com/darkprograms/speech/recognizer/GSpeechDuplex.java) 68 | 69 | - Microphone Capture API is used (Wrapped around the current Java API for simplicity) 70 | - Converts WAVE files from microphone input to FLAC (using existing API, see CREDITS) 71 | - Retrieves Response from Google, including confidence score and text 72 | 73 | ##### Keep in mind that: 74 | >It doesn't currently support the new official [Google Cloud Speech API](https://cloud.google.com/speech/)(which is also free but for a certain amount of words) 75 | 76 | ### Update 2/7/2018 77 | **Check this issue for Official Google Speech Library code solution -> [#4](https://github.com/goxr3plus/java-google-speech-api/issues/4)** 78 | 79 | 80 | >The new Google Cloud Speech API is not supported yet but you can see [here](https://cloud.google.com/speech/docs/reference/libraries#client-libraries-usage-java) the official Alpha Library from supported by Google 81 | 82 | | Create Google Cloud Account | Generate Speech Recognition Private API Keys | 83 | |:-:|:-:| 84 | | [![First](http://img.youtube.com/vi/1sdLrUfMBdI/0.jpg)](https://www.youtube.com/watch?v=1sdLrUfMBdI) | [![Second](http://img.youtube.com/vi/ZUHqMn6NacY/0.jpg)](https://www.youtube.com/watch?v=ZUHqMn6NacY) | 85 | 86 | 87 | **2)** Google translate full support through [GoogleTranslate.java](https://github.com/goxr3plus/java-google-speech-api/blob/master/src/main/java/com/darkprograms/speech/translator/GoogleTranslate.java) 88 | 89 | - A translator using Google Translate (courtesy of Skylion's Google Toolkit) 90 | 91 | | Tutorial 1 | Tutorial 2 | 92 | |:-:|:-:| 93 | | [![First](http://img.youtube.com/vi/H9G02EkohtU/0.jpg)](https://www.youtube.com/watch?v=H9G02EkohtU) | [![Second](http://img.youtube.com/vi/-AMoR_WPV_M/0.jpg)](https://www.youtube.com/watch?v=-AMoR_WPV_M) | 94 | 95 | **3)** Text to Speech , Audio Synthesizer through [SynthesiserV2.java](https://github.com/goxr3plus/java-google-speech-api/blob/master/src/main/java/com/darkprograms/speech/synthesiser/SynthesiserV2.java) 96 | 97 | - Retrieves synthesized text in an InputStream (MP3 data ready to be played) 98 | 99 | | Tutorial 1 | Tutorial 2 | 100 | |:-:|:-:| 101 | | [![First](http://img.youtube.com/vi/42-ZqfPYmVw/0.jpg)](https://www.youtube.com/watch?v=42-ZqfPYmVw) | [![Second](http://img.youtube.com/vi/ckjURDx1JGw/0.jpg)](https://www.youtube.com/watch?v=ckjURDx1JGw) | 102 | 103 | 104 | >The program supports dozens of languages and even has the ability to auto-detect languages! 105 | 106 | # Maven Build 107 | 108 | > Maven Clean Package [ With Javadocs produced ] 109 | 110 | ```mvn clean package``` 111 | 112 | > Maven Clean Package [ No Javadocs produced ] 113 | 114 | ```mvn -Dmaven.javadoc.skip=true clean package``` 115 | 116 | 117 | 118 | ## Java Swing speech recognition example using [GSpeechDuplex.java](https://github.com/goxr3plus/java-google-speech-api/blob/master/src/main/java/com/darkprograms/speech/recognizer/GSpeechDuplex.java) 119 | 120 | ```Java 121 | 122 | package Try_Google_Speech_Recognition_Simple; 123 | 124 | import java.awt.event.ActionEvent; 125 | import java.awt.event.ActionListener; 126 | import java.io.IOException; 127 | 128 | import javax.swing.BoxLayout; 129 | import javax.swing.JButton; 130 | import javax.swing.JFrame; 131 | import javax.swing.JLabel; 132 | import javax.swing.JPanel; 133 | import javax.swing.JScrollPane; 134 | import javax.swing.JTextArea; 135 | 136 | import com.darkprograms.speech.microphone.Microphone; 137 | import com.darkprograms.speech.recognizer.GSpeechDuplex; 138 | import com.darkprograms.speech.recognizer.GSpeechResponseListener; 139 | import com.darkprograms.speech.recognizer.GoogleResponse; 140 | 141 | import net.sourceforge.javaflacencoder.FLACFileWriter; 142 | 143 | public class TryGoogleSpeechRecognitionSimple implements GSpeechResponseListener { 144 | 145 | public static void main(String[] args) throws IOException { 146 | final Microphone mic = new Microphone(FLACFileWriter.FLAC); 147 | // You have to make your own GOOGLE_API_KEY 148 | GSpeechDuplex duplex = new GSpeechDuplex("GOOGLE_API_KEY"); 149 | 150 | duplex.setLanguage("en"); 151 | 152 | JFrame frame = new JFrame("Jarvis Speech API DEMO"); 153 | frame.setDefaultCloseOperation(3); 154 | JTextArea response = new JTextArea(); 155 | response.setEditable(false); 156 | response.setWrapStyleWord(true); 157 | response.setLineWrap(true); 158 | 159 | final JButton record = new JButton("Record"); 160 | final JButton stop = new JButton("Stop"); 161 | stop.setEnabled(false); 162 | 163 | record.addActionListener(new ActionListener() { 164 | public void actionPerformed(ActionEvent evt) { 165 | new Thread(() -> { 166 | try { 167 | duplex.recognize(mic.getTargetDataLine(), mic.getAudioFormat()); 168 | } catch (Exception ex) { 169 | ex.printStackTrace(); 170 | } 171 | 172 | }).start(); 173 | record.setEnabled(false); 174 | stop.setEnabled(true); 175 | } 176 | }); 177 | stop.addActionListener(new ActionListener() { 178 | public void actionPerformed(ActionEvent arg0) { 179 | mic.close(); 180 | duplex.stopSpeechRecognition(); 181 | record.setEnabled(true); 182 | stop.setEnabled(false); 183 | } 184 | }); 185 | JLabel infoText = new JLabel( 186 | "
Just hit record and watch your voice be translated into text.\n
Only English is supported by this demo, but the full API supports dozens of languages.
", 187 | 188 | 0); 189 | frame.getContentPane().add(infoText); 190 | infoText.setAlignmentX(0.5F); 191 | JScrollPane scroll = new JScrollPane(response); 192 | frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), 1)); 193 | frame.getContentPane().add(scroll); 194 | JPanel recordBar = new JPanel(); 195 | frame.getContentPane().add(recordBar); 196 | recordBar.setLayout(new BoxLayout(recordBar, 0)); 197 | recordBar.add(record); 198 | recordBar.add(stop); 199 | frame.setVisible(true); 200 | frame.pack(); 201 | frame.setSize(500, 500); 202 | frame.setLocationRelativeTo(null); 203 | 204 | duplex.addResponseListener(new GSpeechResponseListener() { 205 | String old_text = ""; 206 | 207 | public void onResponse(GoogleResponse gr) { 208 | String output = ""; 209 | output = gr.getResponse(); 210 | if (gr.getResponse() == null) { 211 | this.old_text = response.getText(); 212 | if (this.old_text.contains("(")) { 213 | this.old_text = this.old_text.substring(0, this.old_text.indexOf('(')); 214 | } 215 | System.out.println("Paragraph Line Added"); 216 | this.old_text = ( response.getText() + "\n" ); 217 | this.old_text = this.old_text.replace(")", "").replace("( ", ""); 218 | response.setText(this.old_text); 219 | return; 220 | } 221 | if (output.contains("(")) { 222 | output = output.substring(0, output.indexOf('(')); 223 | } 224 | if (!gr.getOtherPossibleResponses().isEmpty()) { 225 | output = output + " (" + (String) gr.getOtherPossibleResponses().get(0) + ")"; 226 | } 227 | System.out.println(output); 228 | response.setText(""); 229 | response.append(this.old_text); 230 | response.append(output); 231 | } 232 | }); 233 | } 234 | 235 | @Override 236 | public void onResponse(GoogleResponse paramGoogleResponse) { 237 | // TODO Auto-generated method stub 238 | 239 | } 240 | } 241 | 242 | ``` 243 | 244 | 245 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 4 | 4.0.0 5 | 6 | com.darkprograms.speech 7 | java-google-speech-api 8 | 8.0.0 9 | jar 10 | 11 | java-google-speech-api 12 | https://github.com/goxr3plus/java-google-speech-api 13 | 14 | 15 | UTF-8 16 | 1.8 17 | 1.8 18 | 19 | 20 | 21 | 22 | 23 | org.apache.maven.plugins 24 | maven-source-plugin 25 | 3.0.1 26 | 27 | 28 | attach-sources 29 | 30 | jar 31 | 32 | 33 | 34 | 35 | 36 | org.apache.maven.plugins 37 | maven-javadoc-plugin 38 | 3.0.1 39 | 40 | 41 | attach-javadocs 42 | 43 | jar 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | com.github.axet 54 | java-flac-encoder 55 | 0.3.8 56 | 57 | 58 | 59 | org.json 60 | json 61 | 20150729 62 | 63 | 64 | junit 65 | junit 66 | 4.13.1 67 | test 68 | 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /src/main/java/com/goxr3plus/speech/microphone/Microphone.java: -------------------------------------------------------------------------------- 1 | package com.goxr3plus.speech.microphone; 2 | 3 | import javax.sound.sampled.*; 4 | 5 | import java.io.Closeable; 6 | import java.io.File; 7 | 8 | /*************************************************************************** 9 | * Microphone class that contains methods to capture audio from microphone 10 | * 11 | * @author Luke Kuza, Aaron Gokaslan 12 | ***************************************************************************/ 13 | public class Microphone implements Closeable { 14 | 15 | /** 16 | * TargetDataLine variable to receive data from microphone 17 | */ 18 | private TargetDataLine targetDataLine; 19 | 20 | /** 21 | * Enum for current Microphone state 22 | */ 23 | public enum CaptureState { 24 | PROCESSING_AUDIO, STARTING_CAPTURE, CLOSED; 25 | } 26 | 27 | /** 28 | * Variable for enum 29 | */ 30 | CaptureState state; 31 | 32 | /** 33 | * Variable for the audios saved file type 34 | */ 35 | private AudioFileFormat.Type fileType; 36 | 37 | /** 38 | * Variable that holds the saved audio file 39 | */ 40 | private File audioFile; 41 | 42 | /** 43 | * Constructor 44 | * 45 | * @param fileType 46 | * File type to save the audio in
47 | * Example, to save as WAVE use AudioFileFormat.Type.WAVE 48 | */ 49 | public Microphone(AudioFileFormat.Type fileType) { 50 | setState(CaptureState.CLOSED); 51 | setFileType(fileType); 52 | initTargetDataLine(); 53 | } 54 | 55 | /** 56 | * Gets the current state of Microphone 57 | * 58 | * @return PROCESSING_AUDIO is returned when the Thread is recording Audio and/or saving it to a file
59 | * STARTING_CAPTURE is returned if the Thread is setting variables
60 | * CLOSED is returned if the Thread is not doing anything/not capturing audio 61 | */ 62 | public CaptureState getState() { 63 | return state; 64 | } 65 | 66 | /** 67 | * Sets the current state of Microphone 68 | * 69 | * @param state 70 | * State from enum 71 | */ 72 | private void setState(CaptureState state) { 73 | this.state = state; 74 | } 75 | 76 | public File getAudioFile() { 77 | return audioFile; 78 | } 79 | 80 | public void setAudioFile(File audioFile) { 81 | this.audioFile = audioFile; 82 | } 83 | 84 | public AudioFileFormat.Type getFileType() { 85 | return fileType; 86 | } 87 | 88 | public void setFileType(AudioFileFormat.Type fileType) { 89 | this.fileType = fileType; 90 | } 91 | 92 | public TargetDataLine getTargetDataLine() { 93 | return targetDataLine; 94 | } 95 | 96 | public void setTargetDataLine(TargetDataLine targetDataLine) { 97 | this.targetDataLine = targetDataLine; 98 | } 99 | 100 | /** 101 | * Initializes the target data line. 102 | */ 103 | private void initTargetDataLine() { 104 | DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, getAudioFormat()); 105 | try { 106 | setTargetDataLine((TargetDataLine) AudioSystem.getLine(dataLineInfo)); 107 | } catch (LineUnavailableException e) { 108 | e.printStackTrace(); 109 | return; 110 | } 111 | 112 | } 113 | 114 | /** 115 | * Captures audio from the microphone and saves it a file 116 | * 117 | * @param audioFile 118 | * The File to save the audio to 119 | * 120 | */ 121 | public void captureAudioToFile(File audioFile) { 122 | setState(CaptureState.STARTING_CAPTURE); 123 | setAudioFile(audioFile); 124 | 125 | if (getTargetDataLine() == null) { 126 | initTargetDataLine(); 127 | } 128 | 129 | //Get Audio 130 | new Thread(new CaptureThread()).start(); 131 | 132 | } 133 | 134 | /** 135 | * Captures audio from the microphone and saves it a file 136 | * 137 | * @param audioFile 138 | * The fully path (String) to a file you want to save the audio in 139 | */ 140 | public void captureAudioToFile(String audioFile) { 141 | File file = new File(audioFile); 142 | captureAudioToFile(file); 143 | } 144 | 145 | /** 146 | * The audio format to save in 147 | * 148 | * @return Returns AudioFormat to be used later when capturing audio from microphone 149 | */ 150 | public AudioFormat getAudioFormat() { 151 | float sampleRate = 8000.0F; 152 | //8000,11025,16000,22050,44100 153 | int sampleSizeInBits = 16; 154 | //8,16 155 | int channels = 1; 156 | //1,2 157 | boolean signed = true; 158 | //true,false 159 | boolean bigEndian = false; 160 | //true,false 161 | return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian); 162 | } 163 | 164 | /** 165 | * Opens the microphone, starting the targetDataLine. If it's already open, it does nothing. 166 | */ 167 | public void open() { 168 | if (getTargetDataLine() == null) { 169 | initTargetDataLine(); 170 | } 171 | if (!getTargetDataLine().isOpen() && !getTargetDataLine().isRunning() && !getTargetDataLine().isActive()) { 172 | try { 173 | setState(CaptureState.PROCESSING_AUDIO); 174 | getTargetDataLine().open(getAudioFormat()); 175 | getTargetDataLine().start(); 176 | } catch (LineUnavailableException e) { 177 | e.printStackTrace(); 178 | return; 179 | } 180 | } 181 | 182 | } 183 | 184 | /** 185 | * Close the microphone capture, saving all processed audio to the specified file.
186 | * If already closed, this does nothing 187 | */ 188 | public void close() { 189 | if (getState() == CaptureState.CLOSED) { 190 | } else { 191 | getTargetDataLine().stop(); 192 | getTargetDataLine().close(); 193 | setState(CaptureState.CLOSED); 194 | } 195 | } 196 | 197 | /** 198 | * Thread to capture the audio from the microphone and save it to a file 199 | */ 200 | private class CaptureThread implements Runnable { 201 | 202 | /** 203 | * Run method for thread 204 | */ 205 | public void run() { 206 | try { 207 | AudioFileFormat.Type fileTypeX = getFileType(); 208 | File audioFileX = getAudioFile(); 209 | open(); 210 | AudioSystem.write(new AudioInputStream(getTargetDataLine()), fileTypeX, audioFileX); 211 | //Will write to File until it's closed. 212 | } catch (Exception ex) { 213 | ex.printStackTrace(); 214 | } 215 | } 216 | } 217 | 218 | } 219 | -------------------------------------------------------------------------------- /src/main/java/com/goxr3plus/speech/microphone/MicrophoneAnalyzer.java: -------------------------------------------------------------------------------- 1 | package com.goxr3plus.speech.microphone; 2 | 3 | import javax.sound.sampled.AudioFileFormat; 4 | 5 | import com.goxr3plus.speech.util.*; 6 | 7 | /******************************************************************************************** 8 | * Microphone Analyzer class, detects pitch and volume while extending the microphone class. Implemented as a precursor to a Voice Activity Detection 9 | * (VAD) algorithm. Currently can be used for audio data analysis. Dependencies: FFT.java and Complex.java. Both found in the utility package. 10 | * 11 | * @author Aaron Gokaslan 12 | ********************************************************************************************/ 13 | 14 | public class MicrophoneAnalyzer extends Microphone { 15 | 16 | /** 17 | * Constructor 18 | * 19 | * @param fileType 20 | * The file type you want to save in. FLAC recommended. 21 | */ 22 | public MicrophoneAnalyzer(AudioFileFormat.Type fileType) { 23 | super(fileType); 24 | } 25 | 26 | /** 27 | * Gets the volume of the microphone input Interval is 100ms so allow 100ms for this method to run in your code or specify smaller interval. 28 | * 29 | * @return The volume of the microphone input or -1 if data-line is not available 30 | */ 31 | public int getAudioVolume() { 32 | return getAudioVolume(100); 33 | } 34 | 35 | /** 36 | * Gets the volume of the microphone input 37 | * 38 | * @param interval: 39 | * The length of time you would like to calculate the volume over in milliseconds. 40 | * @return The volume of the microphone input or -1 if data-line is not available. 41 | */ 42 | public int getAudioVolume(int interval) { 43 | return calculateAudioVolume(this.getNumOfBytes(interval / 1000d)); 44 | } 45 | 46 | /** 47 | * Gets the volume of microphone input 48 | * 49 | * @param numOfBytes 50 | * The number of bytes you want for volume interpretation 51 | * @return The volume over the specified number of bytes or -1 if data-line is unavailable. 52 | */ 53 | private int calculateAudioVolume(int numOfBytes) { 54 | byte[] data = getBytes(numOfBytes); 55 | if (data == null) 56 | return -1; 57 | return calculateRMSLevel(data); 58 | } 59 | 60 | /** 61 | * Calculates the volume of AudioData which may be buffered data from a data-line. 62 | * 63 | * @param audioData 64 | * The byte[] you want to determine the volume of 65 | * @return the calculated volume of audioData 66 | */ 67 | public static int calculateRMSLevel(byte[] audioData) { 68 | long lSum = 0; 69 | for (int i = 0; i < audioData.length; i++) 70 | lSum = lSum + audioData[i]; 71 | 72 | double dAvg = lSum / audioData.length; 73 | 74 | double sumMeanSquare = 0d; 75 | for (int j = 0; j < audioData.length; j++) 76 | sumMeanSquare = sumMeanSquare + Math.pow(audioData[j] - dAvg, 2d); 77 | 78 | double averageMeanSquare = sumMeanSquare / audioData.length; 79 | return (int) ( Math.pow(averageMeanSquare, 0.5d) + 0.5 ); 80 | } 81 | 82 | /** 83 | * Returns the number of bytes over interval for useful when figuring out how long to record. 84 | * 85 | * @param seconds 86 | * The length in seconds 87 | * @return the number of bytes the microphone will save. 88 | */ 89 | public int getNumOfBytes(int seconds) { 90 | return getNumOfBytes((double) seconds); 91 | } 92 | 93 | /** 94 | * Returns the number of bytes over interval for useful when figuring out how long to record. 95 | * 96 | * @param seconds 97 | * The length in seconds 98 | * @return the number of bytes the microphone will output over the specified time. 99 | */ 100 | public int getNumOfBytes(double seconds) { 101 | return (int) ( seconds * getAudioFormat().getSampleRate() * getAudioFormat().getFrameSize() + .5 ); 102 | } 103 | 104 | /** 105 | * Returns the a byte[] containing the specified number of bytes 106 | * 107 | * @param numOfBytes 108 | * The length of the returned array. 109 | * @return The specified array or null if it cannot. 110 | */ 111 | private byte[] getBytes(int numOfBytes) { 112 | if (getTargetDataLine() != null) { 113 | byte[] data = new byte[numOfBytes]; 114 | this.getTargetDataLine().read(data, 0, numOfBytes); 115 | return data; 116 | } 117 | return null;//If data cannot be read, returns a null array. 118 | } 119 | 120 | /** 121 | * Calculates the fundamental frequency. In other words, it calculates pitch, except pitch is far more subjective and subtle. Also note, that 122 | * readings may occasionally, be in error due to the complex nature of sound. This feature is in Beta 123 | * 124 | * @return The frequency of the sound in Hertz. 125 | */ 126 | public int getFrequency() { 127 | try { 128 | return getFrequency(4096); 129 | } catch (Exception e) { 130 | //This will never happen. Ever... 131 | return -666; 132 | } 133 | } 134 | 135 | /** 136 | * Calculates the frequency based off of the number of bytes. CAVEAT: THE NUMBER OF BYTES MUST BE A MULTIPLE OF 2!!! 137 | * 138 | * @param numOfBytes 139 | * The number of bytes which must be a multiple of 2!!! 140 | * @return The calculated frequency in Hertz. 141 | */ 142 | public int getFrequency(int numOfBytes) { 143 | if (getTargetDataLine() == null) { 144 | return -1; 145 | } 146 | byte[] data = new byte[numOfBytes + 1];//One byte is lost during conversion 147 | this.getTargetDataLine().read(data, 0, numOfBytes); 148 | return getFrequency(data); 149 | } 150 | 151 | /** 152 | * Calculates the frequency based off of the byte array, 153 | * 154 | * @param bytes 155 | * The audioData you want to analyze 156 | * @return The calculated frequency in Hertz. 157 | */ 158 | public int getFrequency(byte[] bytes) { 159 | double[] audioData = this.bytesToDoubleArray(bytes); 160 | audioData = applyHanningWindow(audioData); 161 | Complex[] complex = new Complex[audioData.length]; 162 | for (int i = 0; i < complex.length; i++) { 163 | complex[i] = new Complex(audioData[i], 0); 164 | } 165 | Complex[] fftTransformed = FFT.fft(complex); 166 | return this.calculateFundamentalFrequency(fftTransformed, 4); 167 | } 168 | 169 | /** 170 | * Applies a Hanning Window to the data set. Hanning Windows are used to increase the accuracy of the FFT. One should always apply a window to a 171 | * dataset before applying an FFT 172 | * 173 | * @param The 174 | * data you want to apply the window to 175 | * @return The windowed data set 176 | */ 177 | private double[] applyHanningWindow(double[] data) { 178 | return applyHanningWindow(data, 0, data.length); 179 | } 180 | 181 | /** 182 | * Applies a Hanning Window to the data set. Hanning Windows are used to increase the accuracy of the FFT. One should always apply a window to a 183 | * dataset before applying an FFT 184 | * 185 | * @param The 186 | * data you want to apply the window to 187 | * @param The 188 | * starting index you want to apply a window from 189 | * @param The 190 | * size of the window 191 | * @return The windowed data set 192 | */ 193 | private double[] applyHanningWindow(double[] signal_in , int pos , int size) { 194 | for (int i = pos; i < pos + size; i++) { 195 | int j = i - pos; // j = index into Hann window function 196 | signal_in[i] = ( signal_in[i] * 0.5 * ( 1.0 - Math.cos(2.0 * Math.PI * j / size) ) ); 197 | } 198 | return signal_in; 199 | } 200 | 201 | /** 202 | * This method calculates the fundamental frequency using Harmonic Product Specturm It down samples the FFTData four times and multiplies the 203 | * arrays together to determine the fundamental frequency. This is slightly more computationally expensive, but much more accurate. In simpler 204 | * terms, the function will remove the harmonic frequencies which occur at every N value by finding the lowest common divisor among them. 205 | * 206 | * @param fftData 207 | * The array returned by the FFT 208 | * @param N 209 | * the number of times you wish to downsample. WARNING: The more times you downsample, the lower the maximum detectable frequency is. 210 | * @return The fundamental frequency in Hertz 211 | */ 212 | private int calculateFundamentalFrequency(Complex[] fftData , int N) { 213 | if (N <= 0 || fftData == null) { 214 | return -1; 215 | } //error case 216 | 217 | final int LENGTH = fftData.length;//Used to calculate bin size 218 | fftData = removeNegativeFrequencies(fftData); 219 | Complex[][] data = new Complex[N][fftData.length / N]; 220 | for (int i = 0; i < N; i++) { 221 | for (int j = 0; j < data[0].length; j++) { 222 | data[i][j] = fftData[j * ( i + 1 )]; 223 | } 224 | } 225 | Complex[] result = new Complex[fftData.length / N];//Combines the arrays 226 | for (int i = 0; i < result.length; i++) { 227 | Complex tmp = new Complex(1, 0); 228 | for (int j = 0; j < N; j++) { 229 | tmp = tmp.times(data[j][i]); 230 | } 231 | result[i] = tmp; 232 | } 233 | int index = this.findMaxMagnitude(result); 234 | return index * getFFTBinSize(LENGTH); 235 | } 236 | 237 | /** 238 | * Removes useless data from transform since sound doesn't use complex numbers. 239 | * 240 | * @param The 241 | * data you want to remove the complex transforms from 242 | * @return The cleaned data 243 | */ 244 | private Complex[] removeNegativeFrequencies(Complex[] c) { 245 | Complex[] out = new Complex[c.length / 2]; 246 | for (int i = 0; i < out.length; i++) { 247 | out[i] = c[i]; 248 | } 249 | return out; 250 | } 251 | 252 | /** 253 | * Calculates the FFTbin size based off the length of the the array Each FFTBin size represents the range of frequencies treated as one. For 254 | * example, if the bin size is 5 then the algorithm is precise to within 5hz. Precondition: length cannot be 0. 255 | * 256 | * @param fftDataLength 257 | * The length of the array used to feed the FFT algorithm 258 | * @return FFTBin size 259 | */ 260 | private int getFFTBinSize(int fftDataLength) { 261 | return (int) ( getAudioFormat().getSampleRate() / fftDataLength + .5 ); 262 | } 263 | 264 | /** 265 | * Calculates index of the maximum magnitude in a complex array. 266 | * 267 | * @param The 268 | * Complex[] you want to get max magnitude from. 269 | * @return The index of the max magnitude 270 | */ 271 | private int findMaxMagnitude(Complex[] input) { 272 | //Calculates Maximum Magnitude of the array 273 | double max = Double.MIN_VALUE; 274 | int index = -1; 275 | for (int i = 0; i < input.length; i++) { 276 | Complex c = input[i]; 277 | double tmp = c.getMagnitude(); 278 | if (tmp > max) { 279 | max = tmp; 280 | ; 281 | index = i; 282 | } 283 | } 284 | return index; 285 | } 286 | 287 | /** 288 | * Converts bytes from a TargetDataLine into a double[] allowing the information to be read. NOTE: One byte is lost in the conversion so don't 289 | * expect the arrays to be the same length! 290 | * 291 | * @param bufferData 292 | * The buffer read in from the target data line 293 | * @return The double[] that the buffer has been converted into. 294 | */ 295 | private double[] bytesToDoubleArray(byte[] bufferData) { 296 | final int bytesRecorded = bufferData.length; 297 | final int bytesPerSample = getAudioFormat().getSampleSizeInBits() / 8; 298 | final double amplification = 100.0; // choose a number as you like 299 | double[] micBufferData = new double[bytesRecorded - bytesPerSample + 1]; 300 | for (int index = 0, floatIndex = 0; index < bytesRecorded - bytesPerSample + 1; index += bytesPerSample, floatIndex++) { 301 | double sample = 0; 302 | for (int b = 0; b < bytesPerSample; b++) { 303 | int v = bufferData[index + b]; 304 | if (b < bytesPerSample - 1 || bytesPerSample == 1) { 305 | v &= 0xFF; 306 | } 307 | sample += v << ( b * 8 ); 308 | } 309 | double sample32 = amplification * ( sample / 32768.0 ); 310 | micBufferData[floatIndex] = sample32; 311 | 312 | } 313 | return micBufferData; 314 | } 315 | 316 | } 317 | -------------------------------------------------------------------------------- /src/main/java/com/goxr3plus/speech/recognizer/FlacEncoder.java: -------------------------------------------------------------------------------- 1 | package com.goxr3plus.speech.recognizer; 2 | 3 | import net.sourceforge.javaflacencoder.FLACEncoder; 4 | import net.sourceforge.javaflacencoder.FLACFileOutputStream; 5 | import net.sourceforge.javaflacencoder.StreamConfiguration; 6 | 7 | import javax.sound.sampled.AudioFormat; 8 | import javax.sound.sampled.AudioInputStream; 9 | import javax.sound.sampled.AudioSystem; 10 | import java.io.File; 11 | import java.nio.ByteBuffer; 12 | import java.nio.ByteOrder; 13 | 14 | /************************************************************************************************************* 15 | * Class that contains methods to encode Wave files to FLAC files 16 | * THIS IS THANKS TO THE javaFlacEncoder Project created here: http://sourceforge.net/projects/javaflacencoder/ 17 | ************************************************************************************************************/ 18 | public class FlacEncoder { 19 | 20 | /** 21 | * Constructor 22 | */ 23 | public FlacEncoder() { 24 | 25 | } 26 | 27 | /** 28 | * Converts a wave file to a FLAC file(in order to POST the data to Google and retrieve a response)
29 | * Sample Rate is 8000 by default 30 | * 31 | * @param inputFile Input wave file 32 | * @param outputFile Output FLAC file 33 | */ 34 | public void convertWaveToFlac(File inputFile, File outputFile) { 35 | 36 | 37 | StreamConfiguration streamConfiguration = new StreamConfiguration(); 38 | streamConfiguration.setSampleRate(8000); 39 | streamConfiguration.setBitsPerSample(16); 40 | streamConfiguration.setChannelCount(1); 41 | 42 | 43 | try { 44 | AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(inputFile); 45 | AudioFormat format = audioInputStream.getFormat(); 46 | 47 | int frameSize = format.getFrameSize(); 48 | 49 | FLACEncoder flacEncoder = new FLACEncoder(); 50 | FLACFileOutputStream flacOutputStream = new FLACFileOutputStream(outputFile); 51 | 52 | flacEncoder.setStreamConfiguration(streamConfiguration); 53 | flacEncoder.setOutputStream(flacOutputStream); 54 | 55 | flacEncoder.openFLACStream(); 56 | 57 | int frameLength = (int) audioInputStream.getFrameLength(); 58 | if(frameLength <= AudioSystem.NOT_SPECIFIED){ 59 | frameLength = 16384;//Arbitrary file size 60 | } 61 | int[] sampleData = new int[frameLength]; 62 | byte[] samplesIn = new byte[frameSize]; 63 | 64 | int i = 0; 65 | 66 | while (audioInputStream.read(samplesIn, 0, frameSize) != -1) { 67 | if (frameSize != 1) { 68 | ByteBuffer bb = ByteBuffer.wrap(samplesIn); 69 | bb.order(ByteOrder.LITTLE_ENDIAN); 70 | short shortVal = bb.getShort(); 71 | sampleData[i] = shortVal; 72 | } else { 73 | sampleData[i] = samplesIn[0]; 74 | } 75 | 76 | i++; 77 | } 78 | 79 | sampleData = truncateNullData(sampleData, i); 80 | 81 | flacEncoder.addSamples(sampleData, i); 82 | flacEncoder.encodeSamples(i, false); 83 | flacEncoder.encodeSamples(flacEncoder.samplesAvailableToEncode(), true); 84 | 85 | audioInputStream.close(); 86 | flacOutputStream.close(); 87 | 88 | } catch (Exception ex) { 89 | ex.printStackTrace(); 90 | } 91 | } 92 | 93 | 94 | /** 95 | * Converts a wave file to a FLAC file(in order to POST the data to Google and retrieve a response)
96 | * Sample Rate is 8000 by default 97 | * 98 | * @param inputFile Input wave file 99 | * @param outputFile Output FLAC file 100 | */ 101 | public void convertWaveToFlac(String inputFile, String outputFile) { 102 | convertWaveToFlac(new File(inputFile), new File(outputFile)); 103 | } 104 | 105 | /** 106 | * Used for when the frame length is unknown to shorten the array to prevent huge blank end space 107 | * @param sampleData The int[] array you want to shorten 108 | * @param index The index you want to shorten it to 109 | * @return The shortened array 110 | */ 111 | private int[] truncateNullData(int[] sampleData, int index){ 112 | if(index == sampleData.length) return sampleData; 113 | int[] out = new int[index]; 114 | for(int i = 0; i responseListeners = new ArrayList(); 56 | 57 | /** 58 | * User defined API-KEY 59 | */ 60 | private final String API_KEY; 61 | 62 | /** 63 | * User-defined language 64 | */ 65 | private String language = "auto"; 66 | 67 | /** 68 | * The maximum size the API will tolerate 69 | */ 70 | private static final int MAX_SIZE = 1048576; 71 | 72 | /** 73 | * Per specification, the final chunk of in a ChunkedOutputStream 74 | */ 75 | private static final byte[] FINAL_CHUNK = new byte[]{ '0' , '\r' , '\n' , '\r' , '\n' }; 76 | 77 | /** 78 | * The AudioInputStream used in Upstream Thread 79 | */ 80 | private AudioInputStream ais; 81 | 82 | /** 83 | * Constructor 84 | * 85 | * @param API_KEY 86 | * The API-Key for Google's Speech API. An API key can be obtained by requesting one by following the process shown at this 87 | * url. 88 | */ 89 | public GSpeechDuplex(String API_KEY) { 90 | this.API_KEY = API_KEY; 91 | } 92 | 93 | /** 94 | * Temporary will be deprecated before release 95 | * 96 | * @return The language code 97 | */ 98 | public String getLanguage() { 99 | return language; 100 | } 101 | 102 | /** 103 | * Temporary will be deprecated before release 104 | * 105 | * @param language 106 | * The language code 107 | */ 108 | public void setLanguage(String language) { 109 | this.language = language; 110 | } 111 | 112 | /** 113 | * Send a FLAC file with the specified sampleRate to the Duplex API 114 | * 115 | * @param flacFile 116 | * The file you wish to upload. NOTE: Segment the file if duration is greater than 15 seconds. 117 | * @param sampleRate 118 | * The sample rate of the file. 119 | * @throws IOException 120 | * If something has gone wrong with reading the file 121 | */ 122 | public void recognize(File flacFile , int sampleRate) throws IOException { 123 | recognize(mapFileIn(flacFile), sampleRate); 124 | } 125 | 126 | /** 127 | * Send a byte[] to the URL with a specified sampleRate. NOTE: The byte[] should contain no more than 15 seconds of audio. Chunking is not fully 128 | * implemented as of yet. Will not string data together for context yet. 129 | * 130 | * @param data 131 | * The byte[] you want to send. 132 | * @param sampleRate 133 | * The sample rate of aforementioned byte array. 134 | */ 135 | public void recognize(byte[] data , int sampleRate) { 136 | 137 | if (data.length >= MAX_SIZE) {//Temporary Chunking. Does not allow for Google to gather context. 138 | byte[][] dataArray = chunkAudio(data); 139 | for (byte[] array : dataArray) { 140 | recognize(array, sampleRate); 141 | } 142 | } 143 | 144 | //Generates a unique ID for the response. 145 | final long PAIR = MIN + (long) ( Math.random() * ( ( MAX - MIN ) + 1L ) ); 146 | 147 | //Generates the Downstream URL 148 | final String API_DOWN_URL = GOOGLE_DUPLEX_SPEECH_BASE + "down?maxresults=1&pair=" + PAIR; 149 | 150 | //Generates the Upstream URL 151 | final String API_UP_URL = GOOGLE_DUPLEX_SPEECH_BASE + "up?lang=" + language + "&lm=dictation&client=chromium&pair=" + PAIR + "&key=" + API_KEY; 152 | 153 | //Opens downChannel 154 | this.downChannel(API_DOWN_URL); 155 | //Opens upChannel 156 | this.upChannel(API_UP_URL, chunkAudio(data), sampleRate); 157 | } 158 | 159 | /** 160 | * This method allows you to stream a continuous stream of data to the API. 161 | *

162 | * Note: This feature is experimental. 163 | *

164 | * 165 | * @param tl 166 | * TL 167 | * @param af 168 | * AF 169 | * @throws LineUnavailableException 170 | * If the Line is unavailable 171 | * @throws InterruptedException 172 | * InterruptedException 173 | */ 174 | public void recognize(TargetDataLine tl , AudioFormat af) throws LineUnavailableException , InterruptedException { 175 | //Generates a unique ID for the response. 176 | final long PAIR = MIN + (long) ( Math.random() * ( ( MAX - MIN ) + 1L ) ); 177 | 178 | //Generates the Downstream URL 179 | final String API_DOWN_URL = GOOGLE_DUPLEX_SPEECH_BASE + "down?maxresults=1&pair=" + PAIR; 180 | 181 | //Generates the Upstream URL 182 | final String API_UP_URL = GOOGLE_DUPLEX_SPEECH_BASE + "up?lang=" + language + "&lm=dictation&client=chromium&pair=" + PAIR + "&key=" + API_KEY 183 | + "&continuous=true&interim=true"; //Tells Google to constantly monitor the stream; 184 | 185 | //Opens downChannel 186 | Thread downChannel = this.downChannel(API_DOWN_URL); 187 | 188 | //Opens upChannel 189 | Thread upChannel = this.upChannel(API_UP_URL, tl, af); 190 | try { 191 | downChannel.join(); 192 | upChannel.interrupt(); 193 | upChannel.join(); 194 | } catch (InterruptedException e) { 195 | downChannel.interrupt(); 196 | downChannel.join(); 197 | upChannel.interrupt(); 198 | upChannel.join(); 199 | } 200 | 201 | } 202 | 203 | /** 204 | * This code opens a new Thread that connects to the downstream URL. Due to threading, the best way to handle this is through the use of 205 | * listeners. 206 | * 207 | * @param The 208 | * URL you want to connect to. 209 | */ 210 | private Thread downChannel(String urlStr) { 211 | final String url = urlStr; 212 | Thread downChannelThread = new Thread("Downstream Thread") { 213 | public void run() { 214 | // handler for DOWN channel http response stream - httpsUrlConn 215 | // response handler should manage the connection.... ?? 216 | // assign a TIMEOUT Value that exceeds by a safe factor 217 | // the amount of time that it will take to write the bytes 218 | // to the UPChannel in a fashion that mimics a liveStream 219 | // of the audio at the applicable Bitrate. BR=sampleRate * bits per sample 220 | // Note that the TLS session uses "* SSLv3, TLS alert, Client hello (1): " 221 | // to wake up the listener when there are additional bytes. 222 | // The mechanics of the TLS session should be transparent. Just use 223 | // httpsUrlConn and allow it enough time to do its work. 224 | Scanner inStream = openHttpsConnection(url); 225 | if (inStream == null) { 226 | //ERROR HAS OCCURED 227 | System.out.println("Error has occured"); 228 | return; 229 | } 230 | String response; 231 | while (inStream.hasNext() && ( response = inStream.nextLine() ) != null) { 232 | if (response.length() > 17) {//Prevents blank responses from Firing 233 | GoogleResponse gr = new GoogleResponse(); 234 | parseResponse(response, gr); 235 | fireResponseEvent(gr); 236 | } 237 | } 238 | inStream.close(); 239 | System.out.println("Finished write on down stream..."); 240 | } 241 | }; 242 | downChannelThread.start(); 243 | return downChannelThread; 244 | } 245 | 246 | /** 247 | * Used to initiate the URL chunking for the upChannel. 248 | * 249 | * @param urlStr 250 | * The URL string you want to upload 2 251 | * @param data 252 | * The data you want to send to the URL 253 | * @param sampleRate 254 | * The specified sample rate of the data. 255 | */ 256 | private void upChannel(String urlStr , byte[][] data , int sampleRate) { 257 | final String murl = urlStr; 258 | final byte[][] mdata = data; 259 | final int mSampleRate = sampleRate; 260 | new Thread("Upstream File Thread") { 261 | public void run() { 262 | openHttpsPostConnection(murl, mdata, mSampleRate); 263 | //Google does not return data via this URL 264 | } 265 | }.start(); 266 | } 267 | 268 | /** 269 | * Streams data from the TargetDataLine to the API. 270 | * 271 | * @param urlStr 272 | * The URL to stream to 273 | * @param tl 274 | * The target data line to stream from. 275 | * @param af 276 | * The AudioFormat to stream with.` 277 | * @throws LineUnavailableException 278 | * If cannot open or stream the TargetDataLine. 279 | */ 280 | private Thread upChannel(String urlStr , TargetDataLine tl , AudioFormat af) throws LineUnavailableException { 281 | final String murl = urlStr; 282 | final TargetDataLine mtl = tl; 283 | final AudioFormat maf = af; 284 | if (!mtl.isOpen()) { 285 | mtl.open(maf); 286 | mtl.start(); 287 | } 288 | Thread upChannelThread = new Thread("Upstream Thread") { 289 | public void run() { 290 | openHttpsPostConnection(murl, mtl, (int) maf.getSampleRate()); 291 | } 292 | }; 293 | upChannelThread.start(); 294 | return upChannelThread; 295 | 296 | } 297 | 298 | /** 299 | * Opens a HTTPS connection to the specified URL string 300 | * 301 | * @param urlStr 302 | * The URL you want to visit 303 | * @return The Scanner to access aforementioned data. 304 | */ 305 | private Scanner openHttpsConnection(String urlStr) { 306 | int resCode = -1; 307 | try { 308 | URL url = new URL(urlStr); 309 | URLConnection urlConn = url.openConnection(); 310 | if (! ( urlConn instanceof HttpsURLConnection )) { 311 | throw new IOException("URL is not an Https URL"); 312 | } 313 | HttpsURLConnection httpConn = (HttpsURLConnection) urlConn; 314 | httpConn.setAllowUserInteraction(false); 315 | // TIMEOUT is required 316 | httpConn.setInstanceFollowRedirects(true); 317 | httpConn.setRequestMethod("GET"); 318 | httpConn.connect(); 319 | resCode = httpConn.getResponseCode(); 320 | if (resCode == HttpsURLConnection.HTTP_OK) { 321 | return new Scanner(httpConn.getInputStream(), "UTF-8"); 322 | } else { 323 | System.out.println("Error: " + resCode); 324 | } 325 | } catch (MalformedURLException e) { 326 | e.printStackTrace(); 327 | } catch (IOException e) { 328 | e.printStackTrace(); 329 | } 330 | return null; 331 | } 332 | 333 | /** 334 | * Opens a HTTPSPostConnection that posts data from a TargetDataLine input 335 | * 336 | * @param murl 337 | * The URL you want to post to. 338 | * @param mtl 339 | * The TargetDataLine you want to post data from. Note should be open 340 | */ 341 | private void openHttpsPostConnection(String murl , TargetDataLine mtl , int sampleRate) { 342 | URL url; 343 | try { 344 | url = new URL(murl); 345 | HttpsURLConnection httpConn = getHttpsURLConnection(sampleRate, url); 346 | // this opens a connection, then sends POST & headers. 347 | final OutputStream out = httpConn.getOutputStream(); 348 | //Note : if the audio is more than 15 seconds 349 | // don't write it to UrlConnInputStream all in one block as this sample does. 350 | // Rather, segment the byteArray and on intermittently, sleeping thread 351 | // supply bytes to the urlConn Stream at a rate that approaches 352 | // the bitrate ( =30K per sec. in this instance ). 353 | System.out.println("Starting to write data to output..."); 354 | ais = new AudioInputStream(mtl); 355 | 356 | AudioSystem.write(ais, FLACFileWriter.FLAC, out); 357 | //Output Stream is automatically closed 358 | // do you need the trailer? 359 | // NOW you can look at the status. 360 | 361 | //Diagonostic Code. 362 | /* 363 | * int resCode = httpConn.getResponseCode(); if (resCode / 100 != 2) { System.out.println("ERROR"); } Scanner scanner = new 364 | * Scanner(httpConn.getInputStream()); while(scanner.hasNextLine()){ System.out.println("UPSTREAM READS:" + scanner.nextLine()); } 365 | * scanner.close(); 366 | */ 367 | System.out.println("Upstream Closed..."); 368 | } catch (IOException ex) { 369 | ex.printStackTrace(); 370 | } 371 | } 372 | 373 | /** 374 | * Force HttpsPostConnection Thread to Stop , Closes this audio input stream and releases any system resources associated with the stream. 375 | */ 376 | public void stopSpeechRecognition() { 377 | //AudioInputStream != null 378 | if (ais != null) 379 | try { 380 | //Close the AudioInput Stream 381 | //so forcing AudioSystem.write(....) to exit , so UpStream Thread will be closed 382 | ais.close(); 383 | } catch (Exception ex) { //catch a general exception here to have our mind peaceful 384 | ex.printStackTrace(); 385 | } 386 | 387 | } 388 | 389 | /** 390 | * Opens a chunked HTTPS post connection and returns a Scanner with incoming data from Google Server Used for to get UPStream Chunked HTTPS 391 | * ensures unlimited file size. 392 | * 393 | * @param urlStr 394 | * The String for the URL 395 | * @param data 396 | * The data you want to send the server 397 | * @param sampleRate 398 | * The sample rate of the flac file. 399 | * @return A Scanner to access the server response. (Probably will never be used) 400 | */ 401 | private Scanner openHttpsPostConnection(String urlStr , byte[][] data , int sampleRate) { 402 | byte[][] mextrad = data; 403 | int resCode = -1; 404 | OutputStream out = null; 405 | // int http_status; 406 | try { 407 | URL url = new URL(urlStr); 408 | HttpsURLConnection httpConn = getHttpsURLConnection(sampleRate, url); 409 | // this opens a connection, then sends POST & headers. 410 | out = httpConn.getOutputStream(); 411 | //Note : if the audio is more than 15 seconds 412 | // dont write it to UrlConnInputStream all in one block as this sample does. 413 | // Rather, segment the byteArray and on intermittently, sleeping thread 414 | // supply bytes to the urlConn Stream at a rate that approaches 415 | // the bitrate ( =30K per sec. in this instance ). 416 | System.out.println("Starting to write"); 417 | for (byte[] dataArray : mextrad) { 418 | out.write(dataArray); // one big block supplied instantly to the underlying chunker wont work for duration > 15 s. 419 | try { 420 | Thread.sleep(1000);//Delays the Audio so Google thinks its a mic. 421 | } catch (InterruptedException e) { 422 | e.printStackTrace(); 423 | } 424 | } 425 | out.write(FINAL_CHUNK); 426 | System.out.println("IO WRITE DONE"); 427 | // do you need the trailer? 428 | // NOW you can look at the status. 429 | resCode = httpConn.getResponseCode(); 430 | if (resCode / 100 != 2) { 431 | System.out.println("ERROR"); 432 | } 433 | if (resCode == HttpsURLConnection.HTTP_OK) { 434 | return new Scanner(httpConn.getInputStream(), "UTF-8"); 435 | } else { 436 | System.out.println("HELP: " + resCode); 437 | } 438 | } catch (MalformedURLException e) { 439 | e.printStackTrace(); 440 | } catch (IOException e) { 441 | e.printStackTrace(); 442 | } 443 | return null; 444 | } 445 | 446 | /** 447 | * @param sampleRate 448 | * The samleRate 449 | * @param url 450 | * The URL 451 | * @return The HTTPSURLConnection 452 | * @throws IOException 453 | * if something goes wrong in reading the file. 454 | */ 455 | private HttpsURLConnection getHttpsURLConnection(int sampleRate , URL url) throws IOException { 456 | URLConnection urlConn = url.openConnection(); 457 | if (! ( urlConn instanceof HttpsURLConnection )) { 458 | throw new IOException("URL is not an Https URL"); 459 | } 460 | HttpsURLConnection httpConn = (HttpsURLConnection) urlConn; 461 | httpConn.setAllowUserInteraction(false); 462 | httpConn.setInstanceFollowRedirects(true); 463 | httpConn.setRequestMethod("POST"); 464 | httpConn.setDoOutput(true); 465 | httpConn.setChunkedStreamingMode(0); 466 | httpConn.setRequestProperty("Transfer-Encoding", "chunked"); 467 | httpConn.setRequestProperty("Content-Type", "audio/x-flac; rate=" + sampleRate); 468 | // also worked with ("Content-Type", "audio/amr; rate=8000"); 469 | httpConn.connect(); 470 | return httpConn; 471 | } 472 | 473 | /** 474 | * Converts the file into a byte[]. Also Android compatible. :) 475 | * 476 | * @param infile 477 | * The File you want to get the byte[] from. 478 | * @return The byte[] 479 | * @throws IOException 480 | * if something goes wrong in reading the file. 481 | */ 482 | private byte[] mapFileIn(File infile) throws IOException { 483 | return Files.readAllBytes(infile.toPath()); 484 | } 485 | 486 | /** 487 | * Parses the String into a GoogleResponse object 488 | * 489 | * @param rawResponse 490 | * The String you want to parse 491 | * @param gr 492 | * the GoogleResponse object to save the data into. 493 | */ 494 | private void parseResponse(String rawResponse , GoogleResponse gr) { 495 | if (rawResponse == null || !rawResponse.contains("\"result\"") || rawResponse.equals("{\"result\":[]}")) { 496 | return; 497 | } 498 | gr.getOtherPossibleResponses().clear(); // Emptys the list 499 | if (rawResponse.contains("\"confidence\":")) { 500 | String confidence = StringUtil.substringBetween(rawResponse, "\"confidence\":", "}"); 501 | gr.setConfidence(confidence); 502 | } else { 503 | gr.setConfidence(String.valueOf(1)); 504 | } 505 | String response = StringUtil.substringBetween(rawResponse, "[{\"transcript\":\"", "\"}],"); 506 | if (response == null) { 507 | response = StringUtil.substringBetween(rawResponse, "[{\"transcript\":\"", "\",\""); 508 | } 509 | gr.setResponse(response); 510 | gr.setFinalResponse(rawResponse.contains("\"final\":true")); 511 | String[] currentHypos = rawResponse.split("\\[\\{\"transcript\":\""); 512 | for (int i = 2; i < currentHypos.length; i++) { 513 | String cleaned = currentHypos[i].substring(0, currentHypos[i].indexOf('\"')); 514 | gr.getOtherPossibleResponses().add(cleaned); 515 | } 516 | } 517 | 518 | /** 519 | * Adds GSpeechResponse Listeners that fire when Google sends a response. 520 | * 521 | * @param rl 522 | * The Listeners you want to add 523 | */ 524 | public synchronized void addResponseListener(GSpeechResponseListener rl) { 525 | responseListeners.add(rl); 526 | } 527 | 528 | /** 529 | * Removes GSpeechResponseListeners that fire when Google sends a response. 530 | * 531 | * @param rl 532 | * The Listeners you want to remove 533 | */ 534 | public synchronized void removeResponseListener(GSpeechResponseListener rl) { 535 | responseListeners.remove(rl); 536 | } 537 | 538 | /** 539 | * Fires responseListeners 540 | * 541 | * @param gr 542 | * The Google Response (in this case the response event). 543 | */ 544 | private synchronized void fireResponseEvent(GoogleResponse gr) { 545 | for (GSpeechResponseListener gl : responseListeners) { 546 | gl.onResponse(gr); 547 | } 548 | } 549 | 550 | /** 551 | * Chunks audio into smaller chunks to stream to the duplex API 552 | * 553 | * @param data 554 | * The data you want to break into smaller pieces 555 | * @return the byte[][] containing on array of chunks. 556 | */ 557 | private byte[][] chunkAudio(byte[] data) { 558 | if (data.length >= MAX_SIZE) {//If larger than 1MB 559 | int frame = MAX_SIZE / 2; 560 | int numOfChunks = (int) ( data.length / ( (double) frame ) ) + 1; 561 | byte[][] data2D = new byte[numOfChunks][]; 562 | for (int i = 0, j = 0; i < data.length && j < data2D.length; i += frame, j++) { 563 | int length = ( data.length - i < frame ) ? data.length - i : frame; 564 | data2D[j] = new byte[length]; 565 | System.arraycopy(data, i, data2D[j], 0, length); 566 | } 567 | return data2D; 568 | } else { 569 | byte[][] tmpData = new byte[1][data.length]; 570 | System.arraycopy(data, 0, tmpData[0], 0, data.length); 571 | return tmpData; 572 | } 573 | } 574 | } 575 | -------------------------------------------------------------------------------- /src/main/java/com/goxr3plus/speech/recognizer/GSpeechResponseListener.java: -------------------------------------------------------------------------------- 1 | package com.goxr3plus.speech.recognizer; 2 | 3 | /** 4 | * Response listeners for URL connections. 5 | * @author Skylion 6 | * 7 | */ 8 | public interface GSpeechResponseListener { 9 | 10 | public void onResponse(GoogleResponse gr); 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/goxr3plus/speech/recognizer/GoogleResponse.java: -------------------------------------------------------------------------------- 1 | package com.goxr3plus.speech.recognizer; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /****************************************************************************** 7 | * Class that holds the response and confidence of a Google recognizer request 8 | * 9 | * @author Luke Kuza, Duncan Jauncey, Aaron Gokaslan 10 | ******************************************************************************/ 11 | public class GoogleResponse { 12 | 13 | /** 14 | * Variable that holds the response 15 | */ 16 | private String response; 17 | /** 18 | * Variable that holds the confidence score 19 | */ 20 | private String confidence; 21 | 22 | /** 23 | * List that holds other possible responses for this request. 24 | */ 25 | private List otherPossibleResponses = new ArrayList(20); 26 | 27 | 28 | private boolean finalResponse = true; 29 | /** 30 | * Constructor 31 | */ 32 | public GoogleResponse() { 33 | 34 | } 35 | 36 | 37 | /** 38 | * Gets the response text of what was said in the submitted Audio to Google 39 | * 40 | * @return String representation of what was said 41 | */ 42 | public String getResponse() { 43 | return response; 44 | } 45 | 46 | /** 47 | * Set the response 48 | * 49 | * @param response The response 50 | */ 51 | protected void setResponse(String response) { 52 | this.response = response; 53 | } 54 | 55 | /** 56 | * Gets the confidence score for the specific request 57 | * 58 | * @return The confidence score, ex .922343324323 59 | */ 60 | public String getConfidence() { 61 | return confidence; 62 | } 63 | 64 | /** 65 | * Set the confidence score for this request 66 | * 67 | * @param confidence The confidence score 68 | */ 69 | protected void setConfidence(String confidence) { 70 | this.confidence = confidence; 71 | } 72 | 73 | /** 74 | * Get other possible responses for this request. 75 | * @return other possible responses 76 | */ 77 | public List getOtherPossibleResponses() { 78 | return otherPossibleResponses; 79 | } 80 | 81 | /** 82 | * Gets all returned responses for this request 83 | * @return All returned responses 84 | */ 85 | public List getAllPossibleResponses() { 86 | List tmp = otherPossibleResponses; 87 | tmp.add(0,response); 88 | return tmp; 89 | } 90 | 91 | public boolean isFinalResponse() { 92 | return finalResponse; 93 | } 94 | 95 | public void setFinalResponse(boolean finalResponse) { 96 | this.finalResponse = finalResponse; 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/main/java/com/goxr3plus/speech/recognizer/Languages.java: -------------------------------------------------------------------------------- 1 | package com.goxr3plus.speech.recognizer; 2 | 3 | public enum Languages { 4 | 5 | 6 | AUTO_DETECT("auto"),//tells Google to auto-detect the language 7 | ARABIC_JORDAN("ar-JO"), 8 | ARABIC_LEBANON("ar-LB"), 9 | ARABIC_QATAR("ar-QA"), 10 | ARABIC_UAE("ar-AE"), 11 | ARABIC_MOROCCO("ar-MA"), 12 | ARABIC_IRAQ("ar-IQ"), 13 | ARABIC_ALGERIA("ar-DZ"), 14 | ARABIC_BAHRAIN("ar-BH"), 15 | ARABIC_LYBIA("ar-LY"), 16 | ARABIC_OMAN("ar-OM"), 17 | ARABIC_SAUDI_ARABIA("ar-SA"), 18 | ARABIC_TUNISIA("ar-TN"), 19 | ARABIC_YEMEN("ar-YE"), 20 | BASQUE("eu"), 21 | CATALAN("ca"), 22 | CZECH("cs"), 23 | DUTCH("nl-NL"), 24 | ENGLISH_AUSTRALIA("en-AU"), 25 | ENGLISH_CANADA("en-CA"), 26 | ENGLISH_INDIA("en-IN"), 27 | ENGLISH_NEW_ZEALAND("en-NZ"), 28 | ENGLISH_SOUTH_AFRICA("en-ZA"), 29 | ENGLISH_UK("en-GB"), 30 | ENGLISH_US("en-US"), 31 | FINNISH("fi"), 32 | FRENCH("fr-FR"), 33 | GALICIAN("gl"), 34 | GERMAN("de-DE"), 35 | HEBREW("he"), 36 | HUNGARIAN("hu"), 37 | ICELANDIC("is"), 38 | ITALIAN("it-IT"), 39 | INDONESIAN("id"), 40 | JAPANESE("ja"), 41 | KOREAN("ko"), 42 | LATIN("la"), 43 | CHINESE_SIMPLIFIED("zh-CN"), 44 | CHINESE_TRANDITIONAL("zh-TW"), 45 | CHINESE_HONGKONG("zh-HK"), 46 | CHINESE_CANTONESE("zh-yue"), 47 | MALAYSIAN("ms-MY"), 48 | NORWEGIAN("no-NO"), 49 | POLISH("pl"), 50 | PIG_LATIN("xx-piglatin"), 51 | PORTUGUESE("pt-PT"), 52 | PORTUGUESE_BRASIL("pt-BR"), 53 | ROMANIAN("ro-RO"), 54 | RUSSIAN("ru"), 55 | SERBIAN("sr-SP"), 56 | SLOVAK("sk"), 57 | SPANISH_ARGENTINA("es-AR"), 58 | SPANISH_BOLIVIA("es-BO"), 59 | SPANISH_CHILE("es-CL"), 60 | SPANISH_COLOMBIA("es-CO"), 61 | SPANISH_COSTA_RICA("es-CR"), 62 | SPANISH_DOMINICAN_REPUBLIC("es-DO"), 63 | SPANISH_ECUADOR("es-EC"), 64 | SPANISH_EL_SALVADOR("es-SV"), 65 | SPANISH_GUATEMALA("es-GT"), 66 | SPANISH_HONDURAS("es-HN"), 67 | SPANISH_MEXICO("es-MX"), 68 | SPANISH_NICARAGUA("es-NI"), 69 | SPANISH_PANAMA("es-PA"), 70 | SPANISH_PARAGUAY("es-PY"), 71 | SPANISH_PERU("es-PE"), 72 | SPANISH_PUERTO_RICO("es-PR"), 73 | SPANISH_SPAIN("es-ES"), 74 | SPANISH_US("es-US"), 75 | SPANISH_URUGUAY("es-UY"), 76 | SPANISH_VENEZUELA("es-VE"), 77 | SWEDISH("sv-SE"), 78 | TURKISH("tr"), 79 | ZULU("zu"); 80 | 81 | //TODO Clean Up JavaDoc for Overloaded Methods using @link 82 | 83 | /** 84 | *Stores the LanguageCode 85 | */ 86 | private final String languageCode; 87 | 88 | /** 89 | *Constructor 90 | */ 91 | private Languages(final String languageCode){ 92 | this.languageCode = languageCode; 93 | } 94 | 95 | /** 96 | * @return the languageCode 97 | */ 98 | public String getLanguageCode() { 99 | return languageCode; 100 | } 101 | 102 | @Override 103 | public String toString(){ 104 | return getLanguageCode(); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/main/java/com/goxr3plus/speech/recognizer/Recognizer.java: -------------------------------------------------------------------------------- 1 | package com.goxr3plus.speech.recognizer; 2 | 3 | import java.util.*; 4 | import java.io.*; 5 | import java.net.URL; 6 | import java.net.URLConnection; 7 | import java.nio.charset.Charset; 8 | 9 | import org.json.*; 10 | 11 | /*************************************************************** 12 | * Class that submits FLAC audio and retrieves recognized text 13 | * 14 | * @author Luke Kuza, Duncan Jauncey, Aaron Gokaslan 15 | **************************************************************/ 16 | public class Recognizer { 17 | 18 | /** 19 | * URL to POST audio data and retrieve results 20 | */ 21 | // "http://www.google.com/speech-api/v2/recognize?lang=en-us&key=ADD_YOUR_KEY_HERE&output=json" 22 | private static final String GOOGLE_RECOGNIZER_URL = "http://www.google.com/speech-api/v2/recognize?client=chromium&output=json"; 23 | 24 | private boolean profanityFilter = true; 25 | private String language = null; 26 | private String apikey = null; 27 | 28 | /** 29 | * Constructor 30 | * @param language The Language 31 | * @param apikey The api key 32 | */ 33 | public Recognizer(String language, String apikey) { 34 | this.language = language; 35 | this.apikey = apikey; 36 | } 37 | 38 | /** 39 | * Constructor 40 | * @param language The Languages class for the language you want to designate 41 | * @param apikey The api key 42 | */ 43 | public Recognizer(Languages language, String apikey){ 44 | this.language = language.getLanguageCode(); 45 | this.apikey = apikey; 46 | } 47 | 48 | /** 49 | * Constructor 50 | * @param profanityFilter The profanity Filter 51 | * @param apikey The api key 52 | */ 53 | public Recognizer(boolean profanityFilter, String apikey){ 54 | this.profanityFilter = profanityFilter; 55 | this.apikey = apikey; 56 | } 57 | 58 | /** 59 | * Constructor 60 | * @param language The language 61 | * @param profanityFilter The profanity Filter 62 | * @param apikey The api key 63 | */ 64 | public Recognizer(String language, boolean profanityFilter, String apikey){ 65 | this.language = language; 66 | this.profanityFilter = profanityFilter; 67 | this.apikey = apikey; 68 | } 69 | 70 | /** 71 | * Constructor 72 | * @param language The language 73 | * @param profanityFilter The profanity Filter 74 | * @param apikey The api key 75 | */ 76 | public Recognizer(Languages language, boolean profanityFilter, String apikey){ 77 | this.language = language.getLanguageCode(); 78 | this.profanityFilter = profanityFilter; 79 | this.apikey = apikey; 80 | } 81 | 82 | /** 83 | * Language: Contains all supported languages for Google Speech to Text. 84 | * Setting this to null will make Google use it's own language detection. 85 | * This value is null by default. 86 | * @param language The languages 87 | */ 88 | public void setLanguage(Languages language) { 89 | this.language = language.getLanguageCode(); 90 | } 91 | 92 | /**Language code. This language code must match the language of the speech to be recognized. ex. en-US ru-RU 93 | * This value is null by default. 94 | * @param language The language code. 95 | */ 96 | public void setLanguage(String language) { 97 | this.language = language; 98 | } 99 | 100 | /** 101 | * Returns the state of profanityFilter 102 | * which enables/disables Google's profanity filter (on by default). 103 | * @return profanityFilter 104 | */ 105 | public boolean getProfanityFilter(){ 106 | return profanityFilter; 107 | } 108 | 109 | /** 110 | * Language code. This language code must match the language of the speech to be recognized. ex. en-US ru-RU 111 | * This value is null by default. 112 | * @return language the Google language 113 | */ 114 | public String getLanguage(){ 115 | return language; 116 | } 117 | 118 | public String getApiKey() { 119 | return apikey; 120 | } 121 | 122 | public void setApiKey(String apikey) { 123 | this.apikey = apikey; 124 | } 125 | 126 | /** 127 | * Get recognized data from a Wave file. This method will encode the wave file to a FLAC file 128 | * 129 | * @param waveFile Wave file to recognize 130 | * @param maxResults Maximum number of results to return in response 131 | * @return Returns a GoogleResponse, with the response and confidence score 132 | * @throws IOException Throws exception if something goes wrong 133 | */ 134 | public GoogleResponse getRecognizedDataForWave(File waveFile, int maxResults) throws IOException{ 135 | FlacEncoder flacEncoder = new FlacEncoder(); 136 | File flacFile = new File(waveFile + ".flac"); 137 | 138 | flacEncoder.convertWaveToFlac(waveFile, flacFile); 139 | 140 | GoogleResponse googleResponse = getRecognizedDataForFlac(flacFile, maxResults, 8000); 141 | 142 | //Delete converted FLAC data 143 | flacFile.delete(); 144 | return googleResponse; 145 | } 146 | 147 | /** 148 | * Get recognized data from a Wave file. This method will encode the wave file to a FLAC 149 | * 150 | * @param waveFile Wave file to recognize 151 | * @param maxResults the maximum number of results to return in the response 152 | * NOTE: Sample rate of file must be 8000 unless a custom sample rate is specified. 153 | * @return Returns a GoogleResponse, with the response and confidence score 154 | * @throws IOException Throws exception if something goes wrong 155 | */ 156 | public GoogleResponse getRecognizedDataForWave(String waveFile, int maxResults) throws IOException { 157 | return getRecognizedDataForWave(new File(waveFile), maxResults); 158 | } 159 | 160 | /** 161 | * Get recognized data from a FLAC file. 162 | * 163 | * @param flacFile FLAC file to recognize 164 | * @param maxResults the maximum number of results to return in the response 165 | * NOTE: Sample rate of file must be 8000 unless a custom sample rate is specified. 166 | * @return Returns a GoogleResponse, with the response and confidence score 167 | * @throws IOException Throws exception if something goes wrong 168 | */ 169 | public GoogleResponse getRecognizedDataForFlac(File flacFile, int maxResults) throws IOException { 170 | return getRecognizedDataForFlac(flacFile, maxResults, 8000); 171 | } 172 | 173 | /** 174 | * Get recognized data from a FLAC file. 175 | * 176 | * @param flacFile FLAC file to recognize 177 | * @param maxResults the maximum number of results to return in the response 178 | * @param sampleRate The sampleRate of the file. Default is 8000. 179 | * @return GoogleResponse with the response and confidence score 180 | * @throws IOException if something goes wrong 181 | */ 182 | public GoogleResponse getRecognizedDataForFlac(File flacFile, int maxResults, int sampleRate) throws IOException{ 183 | String [] response = rawRequest(flacFile, maxResults, sampleRate); 184 | GoogleResponse googleResponse = new GoogleResponse(); 185 | parseResponse(response, googleResponse); 186 | return googleResponse; 187 | } 188 | 189 | /** 190 | * Get recognized data from a FLAC file. 191 | * 192 | * @param flacFile FLAC file to recognize 193 | * @param maxResults the maximum number of results to return in the response 194 | * @param sampleRate The sampleRate of the file. Default is 8000. 195 | * @return GoogleResponse, with the response and confidence score 196 | * @throws IOException if something goes wrong 197 | */ 198 | public GoogleResponse getRecognizedDataForFlac(String flacFile, int maxResults, int sampleRate) throws IOException{ 199 | return getRecognizedDataForFlac(new File(flacFile), maxResults, sampleRate); 200 | } 201 | 202 | /** 203 | * Get recognized data from a FLAC file. 204 | * 205 | * @param flacFile FLAC file to recognize 206 | * @param maxResults the maximum number of results to return in the response 207 | * @return Returns a GoogleResponse, with the response and confidence score 208 | * @throws IOException Throws exception if something goes wrong 209 | */ 210 | public GoogleResponse getRecognizedDataForFlac(String flacFile, int maxResults) throws IOException { 211 | return getRecognizedDataForFlac(new File(flacFile), maxResults); 212 | } 213 | 214 | /** 215 | * Get recognized data from a Wave file. This method will encode the wave file to a FLAC. 216 | * This method will automatically set the language to en-US, or English 217 | * 218 | * @param waveFile Wave file to recognize 219 | * @return Returns a GoogleResponse, with the response and confidence score 220 | * @throws IOException Throws exception if something goes wrong 221 | */ 222 | public GoogleResponse getRecognizedDataForWave(File waveFile) throws IOException { 223 | return getRecognizedDataForWave(waveFile, 1); 224 | } 225 | 226 | /** 227 | * Get recognized data from a Wave file. This method will encode the wave file to a FLAC. 228 | * This method will automatically set the language to en-US, or English 229 | * 230 | * @param waveFile Wave file to recognize 231 | * @return Returns a GoogleResponse, with the response and confidence score 232 | * @throws IOException Throws exception if something goes wrong 233 | */ 234 | public GoogleResponse getRecognizedDataForWave(String waveFile) throws IOException { 235 | return getRecognizedDataForWave(waveFile, 1); 236 | } 237 | 238 | /** 239 | * Get recognized data from a FLAC file. 240 | * This method will automatically set the language to en-US, or English 241 | * 242 | * @param flacFile FLAC file to recognize 243 | * @return Returns a GoogleResponse, with the response and confidence score 244 | * @throws IOException Throws exception if something goes wrong 245 | */ 246 | public GoogleResponse getRecognizedDataForFlac(File flacFile) throws IOException { 247 | return getRecognizedDataForFlac(flacFile, 1); 248 | } 249 | 250 | /** 251 | * Get recognized data from a FLAC file. 252 | * This method will automatically set the language to en-US, or English 253 | * 254 | * @param flacFile FLAC file to recognize 255 | * @return Returns a GoogleResponse, with the response and confidence score 256 | * @throws IOException Throws exception if something goes wrong 257 | */ 258 | public GoogleResponse getRecognizedDataForFlac(String flacFile) throws IOException { 259 | return getRecognizedDataForFlac(flacFile, 1); 260 | } 261 | 262 | /** 263 | * Parses the raw response from Google 264 | * 265 | * @param rawResponse The raw, unparsed response from Google 266 | * @return Returns the parsed response in the form of a Google Response. 267 | */ 268 | private void parseResponse(String[] rawResponse, GoogleResponse googleResponse) { 269 | 270 | for(String s : rawResponse) { 271 | JSONObject jsonResponse = new JSONObject(s); 272 | JSONArray jsonResultArray = jsonResponse.getJSONArray("result"); 273 | for(int i = 0; i < jsonResultArray.length(); i++) { 274 | JSONObject jsonAlternativeObject = jsonResultArray.getJSONObject(i); 275 | JSONArray jsonAlternativeArray = jsonAlternativeObject.getJSONArray("alternative"); 276 | double prevConfidence = 0; 277 | for(int j = 0; j < jsonAlternativeArray.length(); j++) { 278 | JSONObject jsonTranscriptObject = jsonAlternativeArray.getJSONObject(j); 279 | String transcript = jsonTranscriptObject.optString("transcript", ""); 280 | double confidence = jsonTranscriptObject.optDouble("confidence", 0.0); 281 | if(confidence > prevConfidence) { 282 | googleResponse.setResponse(transcript); 283 | googleResponse.setConfidence(String.valueOf(confidence)); 284 | prevConfidence = confidence; 285 | } else 286 | googleResponse.getOtherPossibleResponses().add(transcript); 287 | } 288 | } 289 | } 290 | } 291 | 292 | /** 293 | * Performs the request to Google with a file
294 | * Request is buffered 295 | * 296 | * @param inputFile Input files to recognize 297 | * @return Returns the raw, unparsed response from Google 298 | * @throws IOException Throws exception if something went wrong 299 | */ 300 | private String[] rawRequest(File inputFile, int maxResults, int sampleRate) throws IOException{ 301 | URL url; 302 | URLConnection urlConn; 303 | OutputStream outputStream; 304 | BufferedReader br; 305 | 306 | StringBuilder sb = new StringBuilder(GOOGLE_RECOGNIZER_URL); 307 | if( language != null ) { 308 | sb.append("&lang="); 309 | sb.append(language); 310 | } 311 | else{ 312 | sb.append("&lang=auto"); 313 | } 314 | if(apikey != null) { 315 | sb.append("&key="); 316 | sb.append(apikey); 317 | } 318 | 319 | if( !profanityFilter ) { 320 | sb.append("&pfilter=0"); 321 | } 322 | sb.append("&maxresults="); 323 | sb.append(maxResults); 324 | 325 | // URL of Remote Script. 326 | url = new URL(sb.toString()); 327 | // System.out.println("Recognizer.rawRequest(): url=" + url); 328 | 329 | // Open New URL connection channel. 330 | urlConn = url.openConnection(); 331 | 332 | // we want to do output. 333 | urlConn.setDoOutput(true); 334 | 335 | // No caching 336 | urlConn.setUseCaches(false); 337 | 338 | // Specify the header content type. 339 | urlConn.setRequestProperty("Content-Type", "audio/x-flac; rate=" + sampleRate); 340 | urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) " 341 | + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.52 Safari/537.36"); 342 | 343 | // Send POST output. 344 | outputStream = urlConn.getOutputStream(); 345 | 346 | FileInputStream fileInputStream = new FileInputStream(inputFile); 347 | 348 | byte[] buffer = new byte[256]; 349 | 350 | while ((fileInputStream.read(buffer, 0, 256)) != -1) { 351 | outputStream.write(buffer, 0, 256); 352 | } 353 | 354 | fileInputStream.close(); 355 | outputStream.close(); 356 | 357 | // Get response data. 358 | br = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), Charset.forName("UTF-8"))); 359 | 360 | List completeResponse = new ArrayList(); 361 | String response = br.readLine(); 362 | while(response != null) { 363 | completeResponse.add(response); 364 | response = br.readLine(); 365 | } 366 | 367 | br.close(); 368 | 369 | // System.out.println("Recognizer.rawRequest() -> completeResponse = " + completeResponse); 370 | return completeResponse.toArray(new String[completeResponse.size()]); 371 | } 372 | } 373 | -------------------------------------------------------------------------------- /src/main/java/com/goxr3plus/speech/recognizer/RecognizerChunked.java: -------------------------------------------------------------------------------- 1 | package com.goxr3plus.speech.recognizer; 2 | 3 | 4 | import java.io.BufferedReader; 5 | import java.io.File; 6 | import java.io.FileInputStream; 7 | import java.io.IOException; 8 | import java.io.InputStreamReader; 9 | import java.io.OutputStream; 10 | import java.net.HttpURLConnection; 11 | import java.net.MalformedURLException; 12 | import java.net.URL; 13 | import java.net.URLConnection; 14 | import java.nio.ByteBuffer; 15 | import java.nio.MappedByteBuffer; 16 | import java.nio.channels.FileChannel; 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | 20 | import javax.net.ssl.HttpsURLConnection; 21 | import javax.xml.ws.http.HTTPException; 22 | 23 | import com.goxr3plus.speech.util.StringUtil; 24 | 25 | /** 26 | * This class uses Google's V2 Hook. The class is returns a chunked respones so listeners must be used. 27 | * The class also requires an API-Key (see Constructor) for details. This class is experimental and 28 | * subject to change as we restructure the API. 29 | * @author Aaron Gokaslan (Skylion) 30 | */ 31 | public class RecognizerChunked { 32 | 33 | /** 34 | * Google's API V2 URL 35 | */ 36 | private static final String GOOGLE_SPEECH_URL_V2 = "https://www.google.com/speech-api/v2/recognize"; 37 | 38 | /** 39 | * API-Key used for requests 40 | */ 41 | private final String API_KEY; 42 | 43 | /** 44 | * The language code Google uses to determine the language 45 | * Default value is "auto" 46 | */ 47 | private String language; 48 | 49 | /** 50 | * Stores the Response Listeners 51 | */ 52 | private List responseListeners = new ArrayList(); 53 | 54 | /** 55 | * Constructor 56 | * @param API_KEY The API-Key for Google's Speech API. An API key can be obtained by requesting 57 | * one by following the process shown at this 58 | * url. 59 | */ 60 | public RecognizerChunked(String API_KEY){ 61 | this.API_KEY = API_KEY; 62 | this.language = "auto"; 63 | } 64 | 65 | /** 66 | * Constructor 67 | * @param API_KEY The API-Key for Google's Speech API. An API key can be obtained by requesting 68 | * one by following the process shown at this 69 | * url. 70 | * @param language The language you want to use (Iso code) 71 | * Note: This function will most likely be deprecated. 72 | */ 73 | public RecognizerChunked(String API_KEY, String language){ 74 | this(API_KEY); 75 | this.language = language; 76 | } 77 | 78 | /** 79 | * The current language the Recognizer is set to use. Returns the ISO-Code otherwise, 80 | * it may return "auto." 81 | * @return The ISO-Code or auto if the language the is not specified. 82 | */ 83 | public String getLanguage(){ 84 | return language; 85 | } 86 | 87 | /** 88 | * Sets the language that the file should return. 89 | * @param language The language as an ISO-Code 90 | */ 91 | public void setLanguage(String language){ 92 | this.language = language; 93 | } 94 | 95 | /** 96 | * Analyzes the file for speech 97 | * @param infile The file you want to analyze for speech. 98 | * @param sampleRate The sample rate of the audioFile. 99 | * @throws IOException if something goes wrong reading the file. 100 | */ 101 | public void getRecognizedDataForFlac(File infile, int sampleRate) throws IOException{ 102 | byte[] data = mapFileIn(infile); 103 | getRecognizedDataForFlac(data, sampleRate); 104 | } 105 | 106 | /** 107 | * Analyzes the file for speech 108 | * @param inFile The file you want to analyze for speech. 109 | * @param sampleRate The sample rate of the audioFile. 110 | * @throws IOException if something goes wrong reading the file. 111 | */ 112 | public void getRecognizedDataForFlac(String inFile, int sampleRate) throws IOException{ 113 | getRecognizedDataForFlac(new File(inFile), sampleRate); 114 | } 115 | 116 | /** 117 | * Recognizes the byte data. 118 | * @param data Byte Data 119 | * @param sampleRate The sample rate 120 | */ 121 | public void getRecognizedDataForFlac(byte[] data, int sampleRate){ 122 | StringBuilder sb = new StringBuilder(GOOGLE_SPEECH_URL_V2); 123 | sb.append("?output=json"); 124 | sb.append("&client=chromium"); 125 | sb.append("&lang=" + language); 126 | sb.append("&key=" + API_KEY); 127 | String url = sb.toString(); 128 | 129 | openHttpsPostConnection(url, data, sampleRate); 130 | } 131 | 132 | /** 133 | * Opens a chunked response HTTPS line to the specified URL 134 | * @param urlStr The URL string to connect for chunking 135 | * @param data The data you want to send to Google. Speech files under 15 seconds long recommended. 136 | * @param sampleRate The sample rate for your audio file. 137 | */ 138 | private void openHttpsPostConnection(final String urlStr, final byte[] data, final int sampleRate) { 139 | new Thread () { 140 | public void run() { 141 | HttpsURLConnection httpConn = null; 142 | ByteBuffer buff = ByteBuffer.wrap(data); 143 | byte[] destdata = new byte[2048]; 144 | int resCode = -1; 145 | OutputStream out = null; 146 | try { 147 | URL url = new URL(urlStr); 148 | URLConnection urlConn = url.openConnection(); 149 | if (!(urlConn instanceof HttpsURLConnection)) { 150 | throw new IOException ("URL must be HTTPS"); 151 | } 152 | httpConn = (HttpsURLConnection)urlConn; 153 | httpConn.setAllowUserInteraction(false); 154 | httpConn.setInstanceFollowRedirects(true); 155 | httpConn.setRequestMethod("POST"); 156 | httpConn.setDoOutput(true); 157 | httpConn.setChunkedStreamingMode(0); //TransferType: chunked 158 | httpConn.setRequestProperty("Content-Type", "audio/x-flac; rate=" + sampleRate); 159 | // this opens a connection, then sends POST & headers. 160 | out = httpConn.getOutputStream(); 161 | //beyond 15 sec duration just simply writing the file 162 | // does not seem to work. So buffer it and delay to simulate 163 | // bufferd microphone delivering stream of speech 164 | // re: net.http.ChunkedOutputStream.java 165 | while(buff.remaining() >= destdata.length){ 166 | buff.get(destdata); 167 | out.write(destdata); 168 | }; 169 | byte[] lastr = new byte[buff.remaining()]; 170 | buff.get(lastr, 0, lastr.length); 171 | out.write(lastr); 172 | out.close(); 173 | resCode = httpConn.getResponseCode(); 174 | if(resCode >= HttpURLConnection.HTTP_UNAUTHORIZED){//Stops here if Google doesn't like us/ 175 | throw new HTTPException(HttpURLConnection.HTTP_UNAUTHORIZED);//Throws 176 | } 177 | String line;//Each line that is read back from Google. 178 | BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); 179 | while ((line = br.readLine( )) != null) { 180 | if(line.length()>19 && resCode > 100 && resCode < HttpURLConnection.HTTP_UNAUTHORIZED){ 181 | GoogleResponse gr = new GoogleResponse(); 182 | parseResponse(line, gr); 183 | fireResponseEvent(gr); 184 | } 185 | } 186 | } catch (MalformedURLException e) { 187 | e.printStackTrace(); 188 | } catch (IOException e) { 189 | e.printStackTrace(); 190 | } 191 | finally { 192 | if(httpConn != null) { 193 | httpConn.disconnect(); 194 | } 195 | } 196 | } 197 | }.start(); 198 | } 199 | 200 | /** 201 | * Converts the file into a byte[]. 202 | * @param infile The File you want to specify 203 | * @return a byte array 204 | * @throws IOException if something goes wrong reading the file. 205 | */ 206 | private byte[] mapFileIn(File infile) throws IOException{ 207 | FileInputStream fis = new FileInputStream(infile); 208 | try{ 209 | FileChannel fc = fis.getChannel(); // Get the file's size and then map it into memory 210 | int sz = (int)fc.size(); 211 | MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); 212 | byte[] data2 = new byte[bb.remaining()]; 213 | bb.get(data2); 214 | return data2; 215 | } 216 | finally{//Ensures resources are closed regardless of whether the action suceeded 217 | fis.close(); 218 | } 219 | } 220 | 221 | /** 222 | * Parses the response into a Google Response 223 | * @param rawResponse The raw String you want to parse 224 | * @param gr The GoogleResponse you want to parse into ti. 225 | */ 226 | private void parseResponse(String rawResponse, GoogleResponse gr){ 227 | if(rawResponse == null || !rawResponse.contains("\"result\"")){ return; } 228 | if(rawResponse.contains("\"confidence\":")){ 229 | String confidence = StringUtil.substringBetween(rawResponse, "\"confidence\":", "}"); 230 | gr.setConfidence(confidence); 231 | } 232 | else{ 233 | gr.setConfidence(String.valueOf(1d)); 234 | } 235 | String array = StringUtil.trimString(rawResponse, "[", "]"); 236 | if(array.contains("[")){ 237 | array = StringUtil.trimString(array, "[", "]"); 238 | } 239 | String[] parts = array.split(","); 240 | gr.setResponse(parseTranscript(parts[0])); 241 | for(int i = 1; i synthText) throws IOException { 47 | //Uses an executor service pool for concurrency. Limit to 1000 threads max. 48 | ExecutorService pool = Executors.newFixedThreadPool(1000); 49 | //Stores the Future (Data that will be returned in the future) 50 | Set> set = new LinkedHashSet>(synthText.size()); 51 | for (String part : synthText) { //Iterates through the list 52 | Callable callable = new MP3DataFetcher(part);//Creates Callable 53 | Future future = pool.submit(callable);//Begins to run Callable 54 | set.add(future);//Adds the response that will be returned to a set. 55 | } 56 | List inputStreams = new ArrayList(set.size()); 57 | for (Future future : set) { 58 | try { 59 | inputStreams.add(future.get());//Gets the returned data from the future. 60 | } catch (ExecutionException e) {//Thrown if the MP3DataFetcher encountered an error. 61 | Throwable ex = e.getCause(); 62 | if (ex instanceof IOException) { 63 | throw (IOException) ex;//Downcasts and rethrows it. 64 | } 65 | } catch (InterruptedException e) {//Will probably never be called, but just in case... 66 | Thread.currentThread().interrupt();//Interrupts the thread since something went wrong. 67 | } 68 | } 69 | return new SequenceInputStream(Collections.enumeration(inputStreams));//Sequences the stream. 70 | } 71 | 72 | /** 73 | * Separates a string into smaller parts so that Google will not reject the request. 74 | * 75 | * @param input 76 | * The string you want to separate 77 | * @return A List of the String fragments from your input.. 78 | */ 79 | protected List parseString(String input) { 80 | return parseString(input, new ArrayList()); 81 | } 82 | 83 | /** 84 | * Separates a string into smaller parts so that Google will not reject the request. 85 | * 86 | * @param input 87 | * The string you want to break up into smaller parts 88 | * @param fragments 89 | * List that you want to add stuff too. If you don't have a List already constructed "new ArrayList()" works 90 | * well. 91 | * @return A list of the fragments of the original String 92 | */ 93 | private List parseString(String input , List fragments) { 94 | if (input.length() <= 100) {//Base Case 95 | fragments.add(input); 96 | return fragments; 97 | } else { 98 | int lastWord = findLastWord(input);//Checks if a space exists 99 | if (lastWord <= 0) { 100 | fragments.add(input.substring(0, 100));//In case you sent gibberish to Google. 101 | return parseString(input.substring(100), fragments); 102 | } else { 103 | fragments.add(input.substring(0, lastWord)); 104 | //Otherwise, adds the last word to the list for recursion. 105 | return parseString(input.substring(lastWord), fragments); 106 | } 107 | } 108 | } 109 | 110 | /** 111 | * Finds the last word in your String (before the index of 99) by searching for spaces and ending punctuation. Will preferably parse on 112 | * punctuation to alleviate mid-sentence pausing 113 | * 114 | * @param input 115 | * The String you want to search through. 116 | * @return The index of where the last word of the string ends before the index of 99. 117 | */ 118 | private int findLastWord(String input) { 119 | if (input.length() < 100) 120 | return input.length(); 121 | int space = -1; 122 | for (int i = 99; i > 0; i--) { 123 | char tmp = input.charAt(i); 124 | if (isEndingPunctuation(tmp)) { 125 | return i + 1; 126 | } 127 | if (space == -1 && tmp == ' ') { 128 | space = i; 129 | } 130 | } 131 | if (space > 0) { 132 | return space; 133 | } 134 | return -1; 135 | } 136 | 137 | /** 138 | * Checks if char is an ending character Ending punctuation for all languages according to Wikipedia (Except for Sanskrit non-unicode) 139 | * 140 | * @param input 141 | * The char you want check 142 | * @return True if it is, false if not. 143 | */ 144 | private boolean isEndingPunctuation(char input) { 145 | return input == '.' || input == '!' || input == '?' || input == ';' || input == ':' || input == '|'; 146 | } 147 | 148 | /** 149 | * Automatically determines the language of the original text 150 | * 151 | * @param text 152 | * represents the text you want to check the language of 153 | * @return the languageCode in ISO-639 154 | * @throws IOException 155 | * if it cannot complete the request 156 | */ 157 | public String detectLanguage(String text) throws IOException { 158 | return GoogleTranslate.detectLanguage(text); 159 | } 160 | 161 | /** 162 | * This class is a callable. A callable is like a runnable except that it can return data and throw exceptions. Useful when using futures. 163 | * Dramatically improves the speed of execution. 164 | * 165 | * @author Aaron Gokaslan (Skylion) 166 | */ 167 | private class MP3DataFetcher implements Callable { 168 | private String synthText; 169 | 170 | public MP3DataFetcher(String synthText) { 171 | this.synthText = synthText; 172 | } 173 | 174 | public InputStream call() throws IOException { 175 | return getMP3Data(synthText); 176 | } 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /src/main/java/com/goxr3plus/speech/synthesiser/Synthesiser.java: -------------------------------------------------------------------------------- 1 | package com.goxr3plus.speech.synthesiser; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.net.URL; 6 | import java.net.URLConnection; 7 | import java.net.URLEncoder; 8 | import java.util.List; 9 | 10 | 11 | 12 | /******************************************************************************* 13 | * Synthesiser class that connects to Google's unoffical API to retrieve data 14 | * 15 | * @author Luke Kuza, Aaron Gokaslan (Skylion) 16 | *******************************************************************************/ 17 | public class Synthesiser extends BaseSynthsiser { 18 | 19 | /** 20 | * URL to query for Google synthesiser 21 | */ 22 | private final static String GOOGLE_SYNTHESISER_URL = "http://translate.google.com/translate_tts"; 23 | 24 | /** 25 | * language of the Text you want to translate 26 | */ 27 | private String languageCode; 28 | 29 | /** 30 | * LANG_XX_XXXX Variables are language codes. 31 | */ 32 | public static final String LANG_AU_ENGLISH = "en-AU"; 33 | public static final String LANG_US_ENGLISH = "en-US"; 34 | public static final String LANG_UK_ENGLISH = "en-GB"; 35 | public static final String LANG_ES_SPANISH = "es"; 36 | public static final String LANG_FR_FRENCH = "fr"; 37 | public static final String LANG_DE_GERMAN = "de"; 38 | public static final String LANG_PT_PORTUGUESE = "pt-pt"; 39 | public static final String LANG_PT_BRAZILIAN = "pt-br"; 40 | //Please add on more regional languages as you find them. Also try to include the accent code if you can can. 41 | 42 | /** 43 | * Constructor 44 | */ 45 | public Synthesiser() { 46 | languageCode = "auto"; 47 | } 48 | 49 | /** 50 | * Constructor that takes language code parameter. Specify to "auto" for language autoDetection 51 | * @param languageCode The language code [ Example "es" for SPANISH ] 52 | */ 53 | public Synthesiser(String languageCode){ 54 | this.languageCode = languageCode; 55 | } 56 | 57 | /** 58 | * Returns the current language code for the Synthesiser. 59 | * Example: English(Generic) = en, English (US) = en-US, English (UK) = en-GB. and Spanish = es; 60 | * @return the current language code parameter 61 | */ 62 | public String getLanguage(){ 63 | return languageCode; 64 | } 65 | 66 | /** 67 | * Note: set language to auto to enable automatic language detection. 68 | * Setting to null will also implement Google's automatic language detection 69 | * @param languageCode The language code you would like to modify languageCode to. 70 | */ 71 | public void setLanguage(String languageCode){ 72 | this.languageCode = languageCode; 73 | } 74 | 75 | @Override 76 | public InputStream getMP3Data(String synthText) throws IOException{ 77 | 78 | String languageCode = this.languageCode;//Ensures retention of language settings if set to auto 79 | 80 | if(languageCode == null || languageCode.equals("") || languageCode.equalsIgnoreCase("auto")){ 81 | languageCode = detectLanguage(synthText);//Detects language 82 | /* NOTE: Detect language relies on an entirely seperate endpoint. 83 | * If the GoogleTranslate API stops working, do not use the auto parameter 84 | * and switch to something else or a best guess. 85 | */ 86 | if(languageCode == null){ 87 | languageCode = "en-us";//Reverts to Default Language if it can't detect it. 88 | //Throw an error message here eventually 89 | } 90 | } 91 | 92 | if(synthText.length()>100){ 93 | List fragments = parseString(synthText);//parses String if too long 94 | String tmp = getLanguage(); 95 | setLanguage(languageCode);//Keeps it from autodetecting each fragment. 96 | InputStream out = getMP3Data(fragments); 97 | setLanguage(tmp);//Reverts it to it's previous Language such as auto. 98 | return out; 99 | } 100 | 101 | String encoded = URLEncoder.encode(synthText, "UTF-8"); //Encode 102 | 103 | StringBuilder sb = new StringBuilder(); 104 | sb.append(GOOGLE_SYNTHESISER_URL); //The base URL prefixed by the query parameter. 105 | sb.append("?tl="); 106 | sb.append(languageCode); //The query parameter to specify the language code. 107 | sb.append("&q="); 108 | sb.append(encoded); //We encode the String using URL Encoder 109 | sb.append("&ie=UTF-8&total=1&idx=0"); //Some unknown parameters needed to make the URL work 110 | sb.append("&textlen="); 111 | sb.append(synthText.length()); //We need some String length now. 112 | sb.append("&client=tw-ob"); //Once again, a weird parameter. 113 | //Client=t no longer works as it requires a token, but client=tw-ob seems to work just fine. 114 | 115 | URL url = new URL(sb.toString()); 116 | // Open New URL connection channel. 117 | URLConnection urlConn = url.openConnection(); //Open connection 118 | 119 | //Adding header for user agent is required 120 | urlConn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) " 121 | + "Gecko/20100101 Firefox/4.0"); 122 | 123 | return urlConn.getInputStream(); 124 | } 125 | } 126 | 127 | -------------------------------------------------------------------------------- /src/main/java/com/goxr3plus/speech/synthesiser/SynthesiserV2.java: -------------------------------------------------------------------------------- 1 | package com.goxr3plus.speech.synthesiser; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.net.URL; 6 | import java.net.URLConnection; 7 | import java.net.URLEncoder; 8 | import java.util.List; 9 | 10 | 11 | /** 12 | * This class uses the V2 version of Google's Text to Speech API. While this class requires an API key, 13 | * the endpoint allows for additional specification of parameters including speed and pitch. 14 | * See the constructor for instructions regarding the API_Key. 15 | * @author Skylion (Aaron Gokaslan) 16 | */ 17 | public class SynthesiserV2 extends BaseSynthsiser { 18 | 19 | private static final String GOOGLE_SYNTHESISER_URL = "https://www.google.com/speech-api/v2/synthesize?enc=mpeg" + 20 | "&client=chromium"; 21 | 22 | /** 23 | * API_KEY used for requests 24 | */ 25 | private final String API_KEY; 26 | 27 | /** 28 | * language of the Text you want to translate 29 | */ 30 | private String languageCode; 31 | 32 | /** 33 | * The pitch of the generated audio 34 | */ 35 | private double pitch = 1.0; 36 | 37 | /** 38 | * The speed of the generated audio 39 | */ 40 | private double speed = 1.0; 41 | 42 | /** 43 | * Constructor 44 | * @param API_KEY The API-Key for Google's Speech API. An API key can be obtained by requesting 45 | * one by following the process shown at this 46 | * url. 47 | */ 48 | public SynthesiserV2(String API_KEY){ 49 | this.API_KEY = API_KEY; 50 | } 51 | 52 | /** 53 | * Returns the current language code for the Synthesiser. 54 | * Example: English(Generic) = en, English (US) = en-US, English (UK) = en-GB. and Spanish = es; 55 | * @return the current language code parameter 56 | */ 57 | public String getLanguage(){ 58 | return languageCode; 59 | } 60 | 61 | /** 62 | * Note: set language to auto to enable automatic language detection. 63 | * Setting to null will also implement Google's automatic language detection 64 | * @param languageCode The language code you would like to modify languageCode to. 65 | */ 66 | public void setLanguage(String languageCode){ 67 | this.languageCode = languageCode; 68 | } 69 | 70 | /** 71 | * @return the pitch 72 | */ 73 | public double getPitch() { 74 | return pitch; 75 | } 76 | 77 | /** 78 | * Sets the pitch of the audio. 79 | * Valid values range from 0 to 2 inclusive. 80 | * Values above 1 correspond to higher pitch, values below 1 correspond to lower pitch. 81 | * @param pitch the pitch to set 82 | */ 83 | public void setPitch(double pitch) { 84 | this.pitch = pitch; 85 | } 86 | 87 | /** 88 | * @return the speed 89 | */ 90 | public double getSpeed() { 91 | return speed; 92 | } 93 | 94 | /** 95 | * Sets the speed of audio. 96 | * Valid values range from 0 to 2 inclusive. 97 | * Values higher than one correspond to faster and vice versa. 98 | * @param speed the speed to set 99 | */ 100 | public void setSpeed(double speed) { 101 | this.speed = speed; 102 | } 103 | 104 | @Override 105 | public InputStream getMP3Data(String synthText) throws IOException{ 106 | 107 | String languageCode = this.languageCode;//Ensures retention of language settings if set to auto 108 | 109 | if(languageCode == null || languageCode.equals("") || languageCode.equalsIgnoreCase("auto")){ 110 | try{ 111 | languageCode = detectLanguage(synthText);//Detects language 112 | if(languageCode == null){ 113 | languageCode = "en-us";//Reverts to Default Language if it can't detect it. 114 | } 115 | } 116 | catch(Exception ex){ 117 | ex.printStackTrace(); 118 | languageCode = "en-us";//Reverts to Default Language if it can't detect it. 119 | } 120 | } 121 | 122 | if(synthText.length()>100){ 123 | List fragments = parseString(synthText);//parses String if too long 124 | String tmp = getLanguage(); 125 | setLanguage(languageCode);//Keeps it from autodetecting each fragment. 126 | InputStream out = getMP3Data(fragments); 127 | setLanguage(tmp);//Reverts it to it's previous Language such as auto. 128 | return out; 129 | } 130 | 131 | 132 | String encoded = URLEncoder.encode(synthText, "UTF-8"); //Encode 133 | 134 | StringBuilder sb = new StringBuilder(GOOGLE_SYNTHESISER_URL); 135 | sb.append("&key=" + API_KEY); 136 | sb.append("&text=" + encoded); 137 | sb.append("&lang=" + languageCode); 138 | 139 | if(speed>=0 && speed<=2.0){ 140 | sb.append("&speed=" + speed/2.0); 141 | } 142 | 143 | if(pitch>=0 && pitch<=2.0){ 144 | sb.append("&pitch=" + pitch/2.0); 145 | } 146 | 147 | URL url = new URL(sb.toString()); //create url 148 | 149 | // Open New URL connection channel. 150 | URLConnection urlConn = url.openConnection(); //Open connection 151 | 152 | urlConn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0"); //Adding header for user agent is required 153 | 154 | return urlConn.getInputStream(); 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/main/java/com/goxr3plus/speech/translator/GoogleTranslate.java: -------------------------------------------------------------------------------- 1 | package com.goxr3plus.speech.translator; 2 | 3 | import java.io.IOException; 4 | import java.io.Reader; 5 | import java.io.UnsupportedEncodingException; 6 | import java.net.URL; 7 | import java.net.URLConnection; 8 | import java.net.URLEncoder; 9 | import java.nio.charset.Charset; 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | import java.util.Locale; 13 | 14 | import org.json.JSONArray; 15 | 16 | /*************************************************************************************************************** 17 | * An API for a Google Translation service in Java. Please Note: This API is unofficial and is not supported by Google. Subject to breakage at any 18 | * time. The translator allows for language detection and translation. Recommended for translation of user interfaces or speech commands. All 19 | * translation services provided via Google Translate 20 | * 21 | * @author Aaron Gokaslan (Skylion) 22 | ***************************************************************************************************************/ 23 | public final class GoogleTranslate { //Class marked as final since all methods are static 24 | 25 | /** 26 | * URL to query for Translation 27 | */ 28 | private static final String GOOGLE_TRANSLATE_URL = "https://translate.googleapis.com/translate_a/single"; 29 | 30 | /** 31 | * Private to prevent instantiation 32 | */ 33 | private GoogleTranslate() { 34 | }; 35 | 36 | /** 37 | * Converts the ISO-639 code into a friendly language code in the user's default language For example, if the language is English and the default 38 | * locale is French, it will return "anglais" Useful for UI Strings 39 | * 40 | * @param languageCode 41 | * The ISO639-1 42 | * @return The language in the user's default language 43 | */ 44 | public static String getDisplayLanguage(String languageCode) { 45 | return ( new Locale(languageCode) ).getDisplayLanguage(); 46 | } 47 | 48 | /** 49 | * Completes the complicated process of generating the URL 50 | * 51 | * @param sourceLanguage 52 | * The source language 53 | * @param targetLanguage 54 | * The target language 55 | * @param text 56 | * The text that you wish to generate 57 | * @return The generated URL as a string. 58 | */ 59 | private static String generateURL(String sourceLanguage , String targetLanguage , String text) throws UnsupportedEncodingException { 60 | String encoded = URLEncoder.encode(text, "UTF-8"); //Encode 61 | StringBuilder sb = new StringBuilder(); 62 | sb.append(GOOGLE_TRANSLATE_URL); 63 | sb.append("?client=webapp"); //The client parameter 64 | sb.append("&hl=en"); //The language of the UI? 65 | sb.append("&sl="); //Source language 66 | sb.append(sourceLanguage); 67 | sb.append("&tl="); //Target language 68 | sb.append(targetLanguage); 69 | sb.append("&q="); 70 | sb.append(encoded); 71 | sb.append("&multires=1");//Necessary but unknown parameters 72 | sb.append("&otf=0"); 73 | sb.append("&pc=0"); 74 | sb.append("&trs=1"); 75 | sb.append("&ssel=0"); 76 | sb.append("&tsel=0"); 77 | sb.append("&kc=1"); 78 | sb.append("&dt=t");//This parameters requests the translated text back. 79 | //Other dt parameters request additional information such as pronunciation, and so on. 80 | //TODO Modify API so that the user may request this additional information. 81 | sb.append("&ie=UTF-8"); //Input encoding 82 | sb.append("&oe=UTF-8"); //Output encoding 83 | sb.append("&tk="); //Token authentication parameter 84 | sb.append(generateToken(text)); 85 | return sb.toString(); 86 | } 87 | 88 | /** 89 | * Automatically determines the language of the original text 90 | * 91 | * @param text 92 | * represents the text you want to check the language of 93 | * @return The ISO-639 code for the language 94 | * @throws IOException 95 | * if it cannot complete the request 96 | */ 97 | public static String detectLanguage(String text) throws IOException { 98 | String urlText = generateURL("auto", "en", text); 99 | URL url = new URL(urlText); //Generates URL 100 | String rawData = urlToText(url);//Gets text from Google 101 | return findLanguage(rawData); 102 | } 103 | 104 | /** 105 | * Automatically translates text to a system's default language according to its locale Useful for creating international applications as you can 106 | * translate UI strings 107 | * 108 | * @see GoogleTranslate#translate(String, String, String) 109 | * @param text 110 | * The text you want to translate 111 | * @return The translated text 112 | * @throws IOException 113 | * if cannot complete request 114 | */ 115 | public static String translate(String text) throws IOException { 116 | return translate(Locale.getDefault().getLanguage(), text); 117 | } 118 | 119 | /** 120 | * Automatically detects language and translate to the targetLanguage. Allows Google to determine source language 121 | * 122 | * @see GoogleTranslate#translate(String, String, String) 123 | * @param targetLanguage 124 | * The language you want to translate into in ISO-639 format 125 | * @param text 126 | * The text you actually want to translate 127 | * @return The translated text. 128 | * @throws IOException 129 | * if it cannot complete the request 130 | */ 131 | public static String translate(String targetLanguage , String text) throws IOException { 132 | return translate("auto", targetLanguage, text); 133 | } 134 | 135 | /** 136 | * Translate text from sourceLanguage to targetLanguage Specifying the sourceLanguage greatly improves accuracy over short Strings 137 | * 138 | * @param sourceLanguage 139 | * The language you want to translate from in ISO-639 format 140 | * @param targetLanguage 141 | * The language you want to translate into in ISO-639 format 142 | * @param text 143 | * The text you actually want to translate 144 | * @return the translated text. 145 | * @throws IOException 146 | * if it cannot complete the request 147 | */ 148 | public static String translate(String sourceLanguage , String targetLanguage , String text) throws IOException { 149 | String urlText = generateURL(sourceLanguage, targetLanguage, text); 150 | URL url = new URL(urlText); 151 | String rawData = urlToText(url);//Gets text from Google 152 | if (rawData == null) { 153 | return null; 154 | } 155 | String[] raw = rawData.split("\"");//Parses the JSON 156 | if (raw.length < 2) { 157 | return null; 158 | } 159 | JSONArray arr = new JSONArray(rawData); 160 | JSONArray arr1 = arr.getJSONArray(0); 161 | StringBuilder trans = new StringBuilder(); 162 | for (int i = 0; i < arr1.length(); i++) { 163 | JSONArray arr2 = arr1.getJSONArray(i); 164 | trans.append(arr2.get(0).toString()); 165 | } 166 | return trans.toString();//Returns the translation 167 | } 168 | 169 | /** 170 | * Converts a URL to Text 171 | * 172 | * @param url 173 | * that you want to generate a String from 174 | * @return The generated String 175 | * @throws IOException 176 | * if it cannot complete the request 177 | */ 178 | private static String urlToText(URL url) throws IOException { 179 | URLConnection urlConn = url.openConnection(); //Open connection 180 | //Adding header for user agent is required. Otherwise, Google rejects the request 181 | urlConn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0"); 182 | Reader r = new java.io.InputStreamReader(urlConn.getInputStream(), Charset.forName("UTF-8"));//Gets Data Converts to string 183 | StringBuilder buf = new StringBuilder(); 184 | while (true) {//Reads String from buffer 185 | int ch = r.read(); 186 | if (ch < 0) 187 | break; 188 | buf.append((char) ch); 189 | } 190 | return buf.toString(); 191 | } 192 | 193 | /** 194 | * Searches RAWData for Language 195 | * 196 | * @param RAWData 197 | * the raw String directly from Google you want to search through 198 | * @return The language parsed from the rawData or en-US (English-United States) if Google cannot determine it. 199 | */ 200 | private static String findLanguage(String rawData) { 201 | for (int i = 0; i + 5 < rawData.length(); i++) { 202 | boolean dashDetected = rawData.charAt(i + 4) == '-'; 203 | if (rawData.charAt(i) == ',' && rawData.charAt(i + 1) == '"' && ( ( rawData.charAt(i + 4) == '"' && rawData.charAt(i + 5) == ',' ) || dashDetected )) { 204 | if (dashDetected) { 205 | int lastQuote = rawData.substring(i + 2).indexOf('"'); 206 | if (lastQuote > 0) 207 | return rawData.substring(i + 2, i + 2 + lastQuote); 208 | } else { 209 | String possible = rawData.substring(i + 2, i + 4); 210 | if (containsLettersOnly(possible)) {//Required due to Google's inconsistent formatting. 211 | return possible; 212 | } 213 | } 214 | } 215 | } 216 | return null; 217 | } 218 | 219 | /** 220 | * Checks if all characters in text are letters. 221 | * 222 | * @param text 223 | * The text you want to determine the validity of. 224 | * @return True if all characters are letter, otherwise false. 225 | */ 226 | private static boolean containsLettersOnly(String text) { 227 | for (int i = 0; i < text.length(); i++) { 228 | if (!Character.isLetter(text.charAt(i))) { 229 | return false; 230 | } 231 | } 232 | return true; 233 | } 234 | 235 | /*************************** 236 | * Cryptography section ************************************************ Thank Dean1510 for the excellent code translation 237 | **************************/ 238 | 239 | //TODO Possibly refactor code as utility class 240 | 241 | /** 242 | * This function generates the int array for translation acting as the seed for the hashing algorithm. 243 | */ 244 | private static int[] TKK() { 245 | return new int[]{ 0x6337E , 0x217A58DC + 0x5AF91132 }; 246 | } 247 | 248 | /** 249 | * An implementation of an unsigned right shift. Necessary since Java does not have unsigned ints. 250 | * 251 | * @param x 252 | * The number you wish to shift. 253 | * @param bits 254 | * The number of bytes you wish to shift. 255 | * @return The shifted number, unsigned. 256 | */ 257 | private static int shr32(int x , int bits) { 258 | if (x < 0) { 259 | long x_l = 0xffffffffl + x + 1; 260 | return (int) ( x_l >> bits ); 261 | } 262 | return x >> bits; 263 | } 264 | 265 | private static int RL(int a , String b) {//I am not entirely sure what this magic does. 266 | for (int c = 0; c < b.length() - 2; c += 3) { 267 | int d = b.charAt(c + 2); 268 | d = d >= 65 ? d - 87 : d - 48; 269 | d = b.charAt(c + 1) == '+' ? shr32(a, d) : ( a << d ); 270 | a = b.charAt(c) == '+' ? ( a + ( d & 0xFFFFFFFF ) ) : a ^ d; 271 | } 272 | return a; 273 | } 274 | 275 | /** 276 | * Generates the token needed for translation. 277 | * 278 | * @param text 279 | * The text you want to generate the token for. 280 | * @return The generated token as a string. 281 | */ 282 | private static String generateToken(String text) { 283 | int tkk[] = TKK(); 284 | int b = tkk[0]; 285 | int e = 0; 286 | int f = 0; 287 | List d = new ArrayList(); 288 | for (; f < text.length(); f++) { 289 | int g = text.charAt(f); 290 | if (0x80 > g) { 291 | d.add(e++, g); 292 | } else { 293 | if (0x800 > g) { 294 | d.add(e++, g >> 6 | 0xC0); 295 | } else { 296 | if (0xD800 == ( g & 0xFC00 ) && f + 1 < text.length() && 0xDC00 == ( text.charAt(f + 1) & 0xFC00 )) { 297 | g = 0x10000 + ( ( g & 0x3FF ) << 10 ) + ( text.charAt(++f) & 0x3FF ); 298 | d.add(e++, g >> 18 | 0xF0); 299 | d.add(e++, g >> 12 & 0x3F | 0x80); 300 | } else { 301 | d.add(e++, g >> 12 | 0xE0); 302 | d.add(e++, g >> 6 & 0x3F | 0x80); 303 | } 304 | } 305 | d.add(e++, g & 63 | 128); 306 | } 307 | } 308 | 309 | int a_i = b; 310 | for (e = 0; e < d.size(); e++) { 311 | a_i += d.get(e); 312 | a_i = RL(a_i, "+-a^+6"); 313 | } 314 | a_i = RL(a_i, "+-3^+b+-f"); 315 | a_i ^= tkk[1]; 316 | long a_l; 317 | if (0 > a_i) { 318 | a_l = 0x80000000l + ( a_i & 0x7FFFFFFF ); 319 | } else { 320 | a_l = a_i; 321 | } 322 | a_l %= Math.pow(10, 6); 323 | return String.format(Locale.US, "%d.%d", a_l, a_l ^ b); 324 | } 325 | } 326 | -------------------------------------------------------------------------------- /src/main/java/com/goxr3plus/speech/util/ChunkedOutputStream.java: -------------------------------------------------------------------------------- 1 | package com.goxr3plus.speech.util; 2 | 3 | //TODO Replace this class with something that isn't 20 years old. 4 | 5 | //ChunkedOutputStream - an OutputStream that implements HTTP/1.1 chunking 6 | // 7 | //Copyright (C) 1996 by Jef Poskanzer . All rights reserved. 8 | // 9 | //Redistribution and use in source and binary forms, with or without 10 | //modification, are permitted provided that the following conditions 11 | //are met: 12 | //1. Redistributions of source code must retain the above copyright 13 | // notice, this list of conditions and the following disclaimer. 14 | //2. Redistributions in binary form must reproduce the above copyright 15 | // notice, this list of conditions and the following disclaimer in the 16 | // documentation and/or other materials provided with the distribution. 17 | // 18 | //THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 19 | //ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | //IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | //ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 22 | //FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | //DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 24 | //OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 25 | //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 26 | //LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 27 | //OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 28 | //SUCH DAMAGE. 29 | // 30 | //Visit the ACME Labs Java page for up-to-date versions of this and other 31 | //fine Java utilities: http://www.acme.com/java/ 32 | 33 | 34 | import java.io.*; 35 | import java.util.*; 36 | 37 | /// An OutputStream that implements HTTP/1.1 chunking. 38 | //

39 | //This class lets a Servlet send its response data as an HTTP/1.1 chunked 40 | //stream. Chunked streams are a way to send arbitrary-length data without 41 | //having to know beforehand how much you're going to send. They are 42 | //introduced by a "Transfer-Encoding: chunked" header, so you have to 43 | //set that header when you make one of these streams. 44 | //

45 | //Sample usage: 46 | //


 47 | //res.setHeader( "Transfer-Encoding", "chunked" );
 48 | //OutputStream out = res.getOutputStream();
 49 | //ChunkedOutputStream chunkOut = new ChunkedOutputStream( out );
 50 | //(write data to chunkOut instead of out)
 51 | //(optionally set footers)
 52 | //chunkOut.done();
 53 | //
54 | //

55 | //Every time the stream gets flushed, a chunk is sent. When done() 56 | //is called, an empty chunk is sent, marking the end of the chunked 57 | //stream as per the chunking spec. 58 | //

59 | //Fetch the software.
60 | //Fetch the entire Acme package. 61 | 62 | public class ChunkedOutputStream extends BufferedOutputStream 63 | { 64 | 65 | private static final byte[] crlf = { 13, 10 }; 66 | private byte[] lenBytes = new byte[20]; // big enough for any number in hex 67 | private List footerNames = new ArrayList(); 68 | private List footerValues = new ArrayList(); 69 | 70 | 71 | /// Make a ChunkedOutputStream with a default buffer size. 72 | // @param out the underlying output stream 73 | public ChunkedOutputStream( OutputStream out ) 74 | { 75 | super( out ); 76 | } 77 | 78 | 79 | /// Make a ChunkedOutputStream with a specified buffer size. 80 | // @param out the underlying output stream 81 | // @param size the buffer size 82 | public ChunkedOutputStream( OutputStream out, int size ) 83 | { 84 | super( out, size ); 85 | } 86 | 87 | /// Flush the stream. This will write any buffered output 88 | // bytes as a chunk. 89 | // @exception IOException if an I/O error occurred 90 | public synchronized void flush() throws IOException 91 | { 92 | if ( count != 0 ) 93 | { 94 | writeBuf( buf, 0, count ); 95 | count = 0; 96 | } 97 | } 98 | 99 | 100 | /// Set a footer. Footers are much like HTTP headers, except that 101 | // they come at the end of the data instead of at the beginning. 102 | public void setFooter( String name, String value ) 103 | { 104 | footerNames.add( name ); 105 | footerValues.add( value ); 106 | } 107 | 108 | 109 | /// Indicate the end of the chunked data by sending a zero-length chunk, 110 | // possible including footers. 111 | // @exception IOException if an I/O error occurred 112 | public void done() throws IOException 113 | { 114 | flush(); 115 | PrintStream pout = new PrintStream( out ); 116 | pout.println( "0" ); 117 | if ( footerNames.size() > 0 ) 118 | { 119 | // Send footers. 120 | for ( int i = 0; i < footerNames.size(); ++i ) 121 | { 122 | String name = footerNames.get( i ); 123 | String value = footerValues.get( i ); 124 | pout.println( name + ": " + value ); 125 | } 126 | } 127 | footerNames = null; 128 | footerValues = null; 129 | pout.println( "" ); 130 | pout.flush(); 131 | } 132 | 133 | 134 | /// Make sure that calling close() terminates the chunked stream. 135 | public void close() throws IOException 136 | { 137 | if ( footerNames != null ) 138 | done(); 139 | super.close(); 140 | } 141 | 142 | 143 | /// Write a sub-array of bytes. 144 | //

145 | // The only reason we have to override the BufferedOutputStream version 146 | // of this is that it writes the array directly to the output stream 147 | // if doesn't fit in the buffer. So we make it use our own chunk-write 148 | // routine instead. Otherwise this is identical to the parent-class 149 | // version. 150 | // @param b the data to be written 151 | // @param off the start offset in the data 152 | // @param len the number of bytes that are written 153 | // @exception IOException if an I/O error occurred 154 | public synchronized void write( byte b[], int off, int len ) throws IOException 155 | { 156 | int avail = buf.length - count; 157 | 158 | if ( len <= avail ) 159 | { 160 | System.arraycopy( b, off, buf, count, len ); 161 | count += len; 162 | return; 163 | } 164 | flush(); 165 | writeBuf( b, off, len ); 166 | } 167 | 168 | /// The only routine that actually writes to the output stream. 169 | // This is where chunking semantics are implemented. 170 | // @exception IOException if an I/O error occurred 171 | @SuppressWarnings("deprecation") 172 | private void writeBuf( byte b[], int off, int len ) throws IOException 173 | { 174 | // Write the chunk length as a hex number. 175 | String lenStr = Integer.toString( len, 16 ); 176 | lenStr.getBytes( 0, lenStr.length(), lenBytes, 0 ); 177 | out.write( lenBytes ); 178 | // Write a CRLF. 179 | out.write( crlf ); 180 | // Write the data. 181 | if ( len != 0 ) 182 | out.write( b, off, len ); 183 | // Write a CRLF. 184 | out.write( crlf ); 185 | // And flush the real stream. 186 | out.flush(); 187 | } 188 | 189 | } 190 | 191 | -------------------------------------------------------------------------------- /src/main/java/com/goxr3plus/speech/util/Complex.java: -------------------------------------------------------------------------------- 1 | package com.goxr3plus.speech.util; 2 | 3 | 4 | /************************************************************************* 5 | * Compilation: javac Complex.java 6 | * Execution: java Complex 7 | * 8 | * Data type for complex numbers. 9 | * 10 | * The data type is "immutable" so once you create and initialize 11 | * a Complex object, you cannot change it. The "final" keyword 12 | * when declaring re and im enforces this rule, making it a 13 | * compile-time error to change the .re or .im fields after 14 | * they've been initialized. 15 | * 16 | * Class based off of Princeton University's Complex.java class 17 | * @author Aaron Gokaslan, Princeton University 18 | *************************************************************************/ 19 | 20 | public class Complex { 21 | private final double re; // the real part 22 | private final double im; // the imaginary part 23 | 24 | // create a new object with the given real and imaginary parts 25 | public Complex(double real, double imag) { 26 | re = real; 27 | im = imag; 28 | } 29 | 30 | // return a string representation of the invoking Complex object 31 | public String toString() { 32 | if (im == 0) return re + ""; 33 | if (re == 0) return im + "i"; 34 | if (im < 0) return re + " - " + (-im) + "i"; 35 | return re + " + " + im + "i"; 36 | } 37 | 38 | // return abs/modulus/magnitude and angle/phase/argument 39 | public double abs() { return Math.hypot(re, im); } // Math.sqrt(re*re + im*im) 40 | public double phase() { return Math.atan2(im, re); } // between -pi and pi 41 | 42 | // return a new Complex object whose value is (this + b) 43 | public Complex plus(Complex b) { 44 | Complex a = this; // invoking object 45 | double real = a.re + b.re; 46 | double imag = a.im + b.im; 47 | return new Complex(real, imag); 48 | } 49 | 50 | // return a new Complex object whose value is (this - b) 51 | public Complex minus(Complex b) { 52 | Complex a = this; 53 | double real = a.re - b.re; 54 | double imag = a.im - b.im; 55 | return new Complex(real, imag); 56 | } 57 | 58 | // return a new Complex object whose value is (this * b) 59 | public Complex times(Complex b) { 60 | Complex a = this; 61 | double real = a.re * b.re - a.im * b.im; 62 | double imag = a.re * b.im + a.im * b.re; 63 | return new Complex(real, imag); 64 | } 65 | 66 | // scalar multiplication 67 | // return a new object whose value is (this * alpha) 68 | public Complex times(double alpha) { 69 | return new Complex(alpha * re, alpha * im); 70 | } 71 | 72 | // return a new Complex object whose value is the conjugate of this 73 | public Complex conjugate() { return new Complex(re, -im); } 74 | 75 | // return a new Complex object whose value is the reciprocal of this 76 | public Complex reciprocal() { 77 | double scale = re*re + im*im; 78 | return new Complex(re / scale, -im / scale); 79 | } 80 | 81 | // return the real or imaginary part 82 | public double re() { return re; } 83 | public double im() { return im; } 84 | 85 | // return a / b 86 | public Complex divides(Complex b) { 87 | Complex a = this; 88 | return a.times(b.reciprocal()); 89 | } 90 | 91 | // return a new Complex object whose value is the complex exponential of this 92 | public Complex exp() { 93 | return new Complex(Math.exp(re) * Math.cos(im), Math.exp(re) * Math.sin(im)); 94 | } 95 | 96 | // return a new Complex object whose value is the complex sine of this 97 | public Complex sin() { 98 | return new Complex(Math.sin(re) * Math.cosh(im), Math.cos(re) * Math.sinh(im)); 99 | } 100 | 101 | // return a new Complex object whose value is the complex cosine of this 102 | public Complex cos() { 103 | return new Complex(Math.cos(re) * Math.cosh(im), -Math.sin(re) * Math.sinh(im)); 104 | } 105 | 106 | // return a new Complex object whose value is the complex tangent of this 107 | public Complex tan() { 108 | return sin().divides(cos()); 109 | } 110 | 111 | // returns the magnitude of the imaginary number. 112 | public double getMagnitude(){ 113 | return Math.sqrt(re*re+im*im); 114 | } 115 | 116 | public boolean equals(Complex other){ 117 | if(other != null) { 118 | return (re == other.re) && (im == other.im); 119 | } 120 | return false; 121 | } 122 | 123 | } 124 | -------------------------------------------------------------------------------- /src/main/java/com/goxr3plus/speech/util/FFT.java: -------------------------------------------------------------------------------- 1 | package com.goxr3plus.speech.util; 2 | 3 | 4 | /************************************************************************* 5 | * Compilation: javac FFT.java 6 | * Execution: java FFT N 7 | * Dependencies: Complex.java 8 | * 9 | * Compute the FFT and inverse FFT of a length N complex sequence. 10 | * Bare bones implementation that runs in O(N log N) time. Our goal 11 | * is to optimize the clarity of the code, rather than performance. 12 | * 13 | * Limitations 14 | * ----------- 15 | * - assumes N is a power of 2 16 | * 17 | * - not the most memory efficient algorithm (because it uses 18 | * an object type for representing complex numbers and because 19 | * it re-allocates memory for the subarray, instead of doing 20 | * in-place or reusing a single temporary array) 21 | * 22 | *************************************************************************/ 23 | 24 | /************************************************************************* 25 | * @author Skylion implementation 26 | * @author Princeton University for the actual algorithm. 27 | ************************************************************************/ 28 | 29 | public class FFT { 30 | 31 | private FFT() {} 32 | 33 | // compute the FFT of x[], assuming its length is a power of 2 34 | public static Complex[] fft(Complex[] x) { 35 | int N = x.length; 36 | 37 | // base case 38 | if (N == 1) return new Complex[] { x[0] }; 39 | 40 | // radix 2 Cooley-Tukey FFT 41 | if (N % 2 != 0) { throw new RuntimeException("N is not a power of 2"); } 42 | 43 | // fft of even terms 44 | Complex[] even = new Complex[N/2]; 45 | for (int k = 0; k < N/2; k++) { 46 | even[k] = x[2*k]; 47 | } 48 | Complex[] q = fft(even); 49 | 50 | // fft of odd terms 51 | Complex[] odd = even; // reuse the array 52 | for (int k = 0; k < N/2; k++) { 53 | odd[k] = x[2*k + 1]; 54 | } 55 | Complex[] r = fft(odd); 56 | 57 | // combine 58 | Complex[] y = new Complex[N]; 59 | for (int k = 0; k < N/2; k++) { 60 | double kth = -2 * k * Math.PI / N; 61 | Complex wk = new Complex(Math.cos(kth), Math.sin(kth)); 62 | y[k] = q[k].plus(wk.times(r[k])); 63 | y[k + N/2] = q[k].minus(wk.times(r[k])); 64 | } 65 | return y; 66 | } 67 | 68 | 69 | // compute the inverse FFT of x[], assuming its length is a power of 2 70 | public static Complex[] ifft(Complex[] x) { 71 | int N = x.length; 72 | Complex[] y = new Complex[N]; 73 | 74 | // take conjugate 75 | for (int i = 0; i < N; i++) { 76 | y[i] = x[i].conjugate(); 77 | } 78 | 79 | // compute forward FFT 80 | y = fft(y); 81 | 82 | // take conjugate again 83 | for (int i = 0; i < N; i++) { 84 | y[i] = y[i].conjugate(); 85 | } 86 | 87 | // divide by N 88 | for (int i = 0; i < N; i++) { 89 | y[i] = y[i].times(1.0 / N); 90 | } 91 | 92 | return y; 93 | 94 | } 95 | 96 | // compute the circular convolution of x and y 97 | public static Complex[] cconvolve(Complex[] x, Complex[] y) { 98 | 99 | // should probably pad x and y with 0s so that they have same length 100 | // and are powers of 2 101 | if (x.length != y.length) { throw new RuntimeException("Dimensions don't agree"); } 102 | 103 | int N = x.length; 104 | 105 | // compute FFT of each sequence 106 | Complex[] a = fft(x); 107 | Complex[] b = fft(y); 108 | 109 | // point-wise multiply 110 | Complex[] c = new Complex[N]; 111 | for (int i = 0; i < N; i++) { 112 | c[i] = a[i].times(b[i]); 113 | } 114 | 115 | // compute inverse FFT 116 | return ifft(c); 117 | } 118 | 119 | 120 | // compute the linear convolution of x and y 121 | public static Complex[] convolve(Complex[] x, Complex[] y) { 122 | Complex ZERO = new Complex(0, 0); 123 | 124 | Complex[] a = new Complex[2*x.length]; 125 | for (int i = 0; i < x.length; i++) a[i] = x[i]; 126 | for (int i = x.length; i < 2*x.length; i++) a[i] = ZERO; 127 | 128 | Complex[] b = new Complex[2*y.length]; 129 | for (int i = 0; i < y.length; i++) b[i] = y[i]; 130 | for (int i = y.length; i < 2*y.length; i++) b[i] = ZERO; 131 | 132 | return cconvolve(a, b); 133 | } 134 | 135 | } 136 | -------------------------------------------------------------------------------- /src/main/java/com/goxr3plus/speech/util/StringUtil.java: -------------------------------------------------------------------------------- 1 | package com.goxr3plus.speech.util; 2 | 3 | /** 4 | * A string utility class for commonly used methods. 5 | * These methods are particularly useful for parsing. 6 | * @author Skylion 7 | */ 8 | public class StringUtil { 9 | 10 | private StringUtil() {};//Prevents instantiation 11 | 12 | /** 13 | * Removes quotation marks from beginning and end of string. 14 | * @param s The string you want to remove the quotation marks from. 15 | * @return The modified String. 16 | */ 17 | public static String stripQuotes(String s) { 18 | int start = 0; 19 | if( s.startsWith("\"") ) { 20 | start = 1; 21 | } 22 | int end = s.length(); 23 | if( s.endsWith("\"") ) { 24 | end = s.length() - 1; 25 | } 26 | return s.substring(start, end); 27 | } 28 | 29 | /** 30 | * Returns the first instance of String found exclusively between part1 and part2. 31 | * @param s The String you want to substring. 32 | * @param part1 The beginning of the String you want to search for. 33 | * @param part2 The end of the String you want to search for. 34 | * @return The String between part1 and part2. 35 | * If the s does not contain part1 or part2, the method returns null. 36 | */ 37 | public static String substringBetween(String s, String part1, String part2) { 38 | String sub = null; 39 | 40 | int i = s.indexOf(part1); 41 | int j = s.indexOf(part2, i + part1.length()); 42 | 43 | if (i != -1 && j != -1) { 44 | int nStart = i + part1.length(); 45 | sub = s.substring(nStart, j); 46 | } 47 | 48 | return sub; 49 | } 50 | 51 | /** 52 | * Gets the string exclusively between the first instance of part1 and the last instance of part2. 53 | * @param s The string you want to trim. 54 | * @param part1 The term to trim after first instance. 55 | * @param part2 The term to before last instance of. 56 | * @return The trimmed String 57 | */ 58 | public static String trimString(String s, String part1, String part2){ 59 | if(!s.contains(part1) || !s.contains(part2)){ 60 | return null; 61 | } 62 | int first = s.indexOf(part1) + part1.length() + 1; 63 | String tmp = s.substring(first); 64 | int last = tmp.lastIndexOf(part2); 65 | tmp = tmp.substring(0, last); 66 | return tmp; 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/test/java/translator/TranslatorTest.java: -------------------------------------------------------------------------------- 1 | package translator; 2 | 3 | import static org.junit.Assert.assertTrue; 4 | 5 | import java.io.IOException; 6 | 7 | import org.junit.Test; 8 | 9 | import com.goxr3plus.speech.translator.GoogleTranslate; 10 | 11 | public class TranslatorTest { 12 | 13 | @Test 14 | public void testString() throws IOException { 15 | 16 | String translatedText = GoogleTranslate.translate("Hola . Buenos días"); 17 | String expecetedText = "Hello . Good morning"; 18 | 19 | System.out.println(translatedText); 20 | assertTrue(translatedText.equals(expecetedText)); 21 | } 22 | } 23 | --------------------------------------------------------------------------------