Annamalai Palanikumar
Annamalai Palanikumar

Reputation: 367

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> 

Upvotes: 1

Views: 327

Answers (2)

VC.One
VC.One

Reputation: 15871

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)

Upvotes: 1

Knight Industries
Knight Industries

Reputation: 1481

While Oracle Nashorn runs ECMA-compliant JavaScript, it is important to note that objects normally accessible in a web browser are not available, for example, console, window, and so on.

source

This also includes the SpeechSynthesis API, which is a Web Browser feature and not part of core JavaScript/ECMA-262.

Upvotes: 2

Related Questions