Java Program For Speech Recognition

-->
  1. Java Program For Calculator
  2. Simple Java Program For Beginners

Quickstarts are also available for speech-to-speech-translation and voice-first virtual assistant.

If desired, choose a different programming language and/or environment:
Nutrition an applied approach 5th edition.

Hello and welcome to another tutorial on Java, In this tutorial we’ll be creating a Voice command application using Java and Sphinx4 Speech Recognition Library for Java. If you are new to this Voice Command term, there are many apps that serve as an example in reality. Install Python Speech Recognition Module. It is a Library for performing speech recognition, with support for several engines and APIs, online and offline. To install it open terminal or command prompt, type the command mentioned below and hit enter. Pip install SpeechRecognition. Python Speech Recognition Program. Java speech-recognition speech speech-synthesis speech-to-text jarvis api google recognition 137 commits. This is a project for the Java Speech API. The program interprets vocal inputs into text and synthesizes voices from text input. The program supports dozens of languages and even has the ability to auto-detect languages! Today, it is also possible to do speech recognition using the computation power of just a browser. Speech recognition is also called speech-to-text. And speech synthesis is also called text-to-speech. Put the text-to-speech code in tts.js and the speech-to-text code in >stt.js. In index.html, just include the two scripts.

In this article, you create a Java console application by using the Speech SDK. You transcribe speech to text in real time from your PC's microphone. The application is built with the Speech SDK Maven package, and the Eclipse Java IDE (v4.8) on 64-bit Windows, 64-bit Linux (Ubuntu 16.04, Ubuntu 18.04, Debian 9), or on macOS 10.13 or later. It runs on a 64-bit Java 8 runtime environment (JRE).

Note

For the Speech Devices SDK and the Roobo device, see Speech Devices SDK.

Prerequisites

This quickstart requires:

  • Operating System: 64-bit Windows, 64-bit Linux (Ubuntu 16.04, Ubuntu 18.04, Debian 9), or macOS 10.13 or later
  • Java 8 or JDK 8
  • An Azure subscription key for the Speech Service. Get one for free.

If you're running Linux, make sure these dependencies are installed before starting Eclipse.

  • On Ubuntu:

  • On Debian 9:

If you're running Windows (64-bit), ensure you have installed Microsoft Visual C++ Redistributable for your platform.

Create and configure project

  1. Start Eclipse.

  2. In the Eclipse Launcher, in the Workspace field, enter the name of a new workspace directory. Then select Launch.

  3. In a moment, the main window of the Eclipse IDE appears. Close the Welcome screen if one is present.

  4. From the Eclipse menu bar, create a new project by choosing File > New > Project.

  5. The New Project dialog box appears. Select Java Project, and select Next.

  6. The New Java Project wizard starts. In the Project name field, enter quickstart, and choose JavaSE-1.8 as the execution environment. Select Finish.

  7. If the Open Associated Perspective? window appears, select Open Perspective.

  8. In the Package explorer, right-click the quickstart project. Choose Configure > Convert to Maven Project from the context menu.

  9. The Create new POM window appears. In the Group Id field, enter com.microsoft.cognitiveservices.speech.samples, and in the Artifact Id field, enter quickstart. Then select Finish.

  10. Open the pom.xml file and edit it.

    • At the end of the file, before the closing tag </project>, create a repositories element with a reference to the Maven repository for the Speech SDK, as shown here:

    • Also add a dependencies element, with the Speech SDK version 1.6.0 as a dependency:

    • Save the changes.

Add sample code

Java Program For Calculator

  1. To add a new empty class to your Java project, select File > New > Class.

  2. In the New Java Class window, enter speechsdk.quickstart into the Package field, and Main into the Name field.

  3. Replace all code in Main.java with the following snippet:

  4. Replace the string YourSubscriptionKey with your subscription key.

  5. Replace the string YourServiceRegion with the region associated with your subscription (for example, westus for the free trial subscription).

  6. Save changes to the project. Adobe acrobat 9 missing pdf maker files error.

Build and run the app

Press F11, or select Run > Debug.The next 15 seconds of speech input from your microphone will be recognized and logged in the console window.

Next steps

For

Additional samples, such as how to read speech from an audio file, are available on GitHub.

See also

  • Sponsor Simple Java Program For Beginners

    GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.

    Sign up
    Find file Copy path
    goxr3plusFixed problem with missing package declaration41c71a1Sep 7, 2017
    1 contributor
    packagemodel;
    importjava.io.IOException;
    importjava.util.List;
    importjava.util.concurrent.ExecutorService;
    importjava.util.concurrent.Executors;
    importjava.util.logging.Level;
    importjava.util.logging.Logger;
    importjavax.sound.sampled.AudioSystem;
    importjavax.sound.sampled.Port;
    importedu.cmu.sphinx.api.Configuration;
    importedu.cmu.sphinx.api.LiveSpeechRecognizer;
    importedu.cmu.sphinx.api.SpeechResult;
    importedu.cmu.sphinx.result.WordResult;
    publicclassSpeechRecognizerMain {
    // Necessary
    privateLiveSpeechRecognizer recognizer;
    // Logger
    privateLogger logger =Logger.getLogger(getClass().getName());
    /**
    * This String contains the Result that is coming back from SpeechRecognizer
    */
    privateString speechRecognitionResult;
    //-----------------Lock Variables-----------------------------
    /**
    * This variable is used to ignore the results of speech recognition cause actually it can't be stopped..
    *
    * <br>
    * Check this link for more information: <a href=
    * 'https://sourceforge.net/p/cmusphinx/discussion/sphinx4/thread/3875fc39/'>https://sourceforge.net/p/cmusphinx/discussion/sphinx4/thread/3875fc39/</a>
    */
    privateboolean ignoreSpeechRecognitionResults =false;
    /**
    * Checks if the speech recognise is already running
    */
    privateboolean speechRecognizerThreadRunning =false;
    /**
    * Checks if the resources Thread is already running
    */
    privateboolean resourcesThreadRunning;
    //---
    /**
    * This executor service is used in order the playerState events to be executed in an order
    */
    privateExecutorService eventsExecutorService =Executors.newFixedThreadPool(2);
    //------------------------------------------------------------------------------------
    /**
    * Constructor
    */
    publicSpeechRecognizerMain() {
    // Loading Message
    logger.log(Level.INFO, 'Loading Speech Recognizer..n');
    // Configuration
    Configuration configuration =newConfiguration();
    // Load model from the jar
    configuration.setAcousticModelPath('resource:/edu/cmu/sphinx/models/en-us/en-us');
    configuration.setDictionaryPath('resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict');
    //
    //READ THIS!!!
    //Uncomment this line of code if you want the recognizer to recognize every word of the language
    //you are using , here it is English for example
    //
    //configuration.setLanguageModelPath('resource:/edu/cmu/sphinx/models/en-us/en-us.lm.bin');
    //
    //READ THIS!!!
    //If you don't want to use a grammar file comment below 3 lines and uncomment the above line for language model
    //
    // Grammar
    configuration.setGrammarPath('resource:/grammars');
    configuration.setGrammarName('grammar');
    configuration.setUseGrammar(true);
    try {
    recognizer =newLiveSpeechRecognizer(configuration);
    } catch (IOException ex) {
    logger.log(Level.SEVERE, null, ex);
    }
    // Start recognition process pruning previously cached data.
    // recognizer.startRecognition(true);
    //Check if needed resources are available
    startResourcesThread();
    //Start speech recognition thread
    startSpeechRecognition();
    }
    //-----------------------------------------------------------------------------------------------
    /**
    * Starts the Speech Recognition Thread
    */
    publicsynchronizedvoidstartSpeechRecognition() {
    //Check lock
    if (speechRecognizerThreadRunning)
    logger.log(Level.INFO, 'Speech Recognition Thread already running..n');
    else
    //Submit to ExecutorService
    eventsExecutorService.submit(() -> {
    //locks
    speechRecognizerThreadRunning =true;
    ignoreSpeechRecognitionResults =false;
    //Start Recognition
    recognizer.startRecognition(true);
    //Information
    logger.log(Level.INFO, 'You can start to speak..n');
    try {
    while (speechRecognizerThreadRunning) {
    /*
    * This method will return when the end of speech is reached. Note that the end pointer will determine the end of speech.
    */
    SpeechResult speechResult = recognizer.getResult();
    //Check if we ignore the speech recognition results
    if (!ignoreSpeechRecognitionResults) {
    //Check the result
    if (speechResult null)
    logger.log(Level.INFO, 'I can't understand what you said.n');
    else {
    //Get the hypothesis
    speechRecognitionResult = speechResult.getHypothesis();
    //You said?
    System.out.println('You said: ['+ speechRecognitionResult +']n');
    //Call the appropriate method
    makeDecision(speechRecognitionResult, speechResult.getWords());
    }
    } else
    logger.log(Level.INFO, 'Ingoring Speech Recognition Results..');
    }
    } catch (Exception ex) {
    logger.log(Level.WARNING, null, ex);
    speechRecognizerThreadRunning =false;
    }
    logger.log(Level.INFO, 'SpeechThread has exited..');
    });
    }
    /**
    * Stops ignoring the results of SpeechRecognition
    */
    publicsynchronizedvoidstopIgnoreSpeechRecognitionResults() {
    //Stop ignoring speech recognition results
    ignoreSpeechRecognitionResults =false;
    }
    /**
    * Ignores the results of SpeechRecognition
    */
    publicsynchronizedvoidignoreSpeechRecognitionResults() {
    //Instead of stopping the speech recognition we are ignoring it's results
    ignoreSpeechRecognitionResults =true;
    }
    //-----------------------------------------------------------------------------------------------
    /**
    * Starting a Thread that checks if the resources needed to the SpeechRecognition library are available
    */
    publicvoidstartResourcesThread() {
    //Check lock
    if (resourcesThreadRunning)
    logger.log(Level.INFO, 'Resources Thread already running..n');
    else
    //Submit to ExecutorService
    eventsExecutorService.submit(() -> {
    try {
    //Lock
    resourcesThreadRunning =true;
    // Detect if the microphone is available
    while (true) {
    //Is the Microphone Available
    if (!AudioSystem.isLineSupported(Port.Info.MICROPHONE))
    logger.log(Level.INFO, 'Microphone is not available.n');
    // Sleep some period
    Thread.sleep(350);
    }
    } catch (InterruptedException ex) {
    logger.log(Level.WARNING, null, ex);
    resourcesThreadRunning =false;
    }
    });
    }
    /**
    * Takes a decision based on the given result
    *
    * @param speechWords
    */
    publicvoidmakeDecision(Stringspeech , List<WordResult>speechWords) {
    System.out.println(speech);
    }
    publicbooleangetIgnoreSpeechRecognitionResults() {
    return ignoreSpeechRecognitionResults;
    }
    publicbooleangetSpeechRecognizerThreadRunning() {
    return speechRecognizerThreadRunning;
    }
    /**
    * Main Method
    *
    * @param args
    */
    publicstaticvoidmain(String[] args) {
    newSpeechRecognizerMain();
    }
    }
    • Copy lines
    • Copy permalink