Search code examples
javascriptjavanashornspeech-synthesisjjs

Getting "speechSynthesis" is not defined in jjs(Java JavaScript)


I am attempting to access the SpeechSynthesis interface for speech service with the help of the Nashorn engine in java. Is it possible to import or create a similar SpeechSynthesis interface to the Nashorn engine Or any other javascript engine with this interface?

Javascript statement to speak "Hello world!"

speechSynthesis.speak(new SpeechSynthesisUtterance("Hello world!"))

In jjs(Java Javascript) tool:

jjs> speechSynthesis.speak(new SpeechSynthesisUtterance("Hello world!"));
<shell>:1 ReferenceError: "speechSynthesis" is not defined
jjs> 

Solution

  • Unfortunately the answer is: No, it's not possible to synthesize speech with Nashorn for Java.

    The real issue (of not working) is because the Speech Synthesis API uses window. a property which is only available from a browser display. See basic code from: SpeechSynthesisUtterance

    var mySynth = window.speechSynthesis; //window must exist for code to work
    

    (1)

    ReferenceError: "speechSynthesis" is not defined

    A more correct way to write your original code would be to declare a variable first:

    jjs> var mySynth = speechSynthesis;
    jjs> mySynth.speak(new SpeechSynthesisUtterance("Hello world!"));
    

    This would cancel the Reference Error: "speechSynthesis" is not defined because your original code is referencing an undefined variable called "speechSynthesis".

    (2)

    "Is it possible to import or create a similar SpeechSynthesis interface to the Nashorn engine Or any other javascript engine with this interface?"

    You cannot use the SpeechSynthesis API in a command-line tool (eg: using JJS). It needs a browser.

    The alternative is to just do the Text-To-Speech part within Java itself.
    You will need a third-part free TTS tool to plug into the Java Speech API.

    Basic tutorial on using Java with OpenTTS (third-party)