I and my team just finished up an awesome POC with our client. We used some really simple tricks to get our 3d character model to speak whatever we typed in the text area in HTML. Before I go into this, you should be aware of Unity, Javascript, HTML.
Believe it or not, but to convert text to speech there is a very simple Javascript function. This function is not difficult to find online when you know the keywords like Speech Synthesis
. Most of the top browsers including Apple’s Safari has this feature. Below is the code which converts Text to Speech,
function Speak(str) {
var msg = new SpeechSynthesisUtterance(str);
msg.lang = ‘en-US’;
msg.volume = 1; // 0 to 1
msg.rate = 1; // 0.1 to 10
msg.pitch = 1; //0 to 2
// stop any TTS that may still be active
window.speechSynthesis.cancel();
window.speechSynthesis.speak(msg);
}
Above function is a simple Javascript code which can be used in any HTML file. And doesn’t require server to run. The above function takes in a parameter “str”. This is the string which you need computer to speak. Call the Speak function and see how the computer speaks.
As its fairly easy to use the above function of JS in your HTML, most developers would prefer that. However if in case you want to access such functionality in C# of unity, you can do following steps.
1: Create a .jslib file (Simple text file) and place it under “Plugins” folder in your “Assets” folder in unity.
2: Edit the .jslib file you created and add below code to it.
var MyPlugin = {
Speak: function(str){
var msg = new SpeechSynthesisUtterance(str);
msg.lang = ‘en-US’;
msg.volume = 1; // 0 to 1
msg.rate = 1; // 0.1 to 10
msg.pitch = 1; //0 to 2
// stop any TTS that may still be active
window.speechSynthesis.cancel();
window.speechSynthesis.speak(msg);
}
}
3: Now you are ready to use this function in your MonoBehaviour C# code. Add the “using System.Runtime.InteropServices;” on top of the C# file.
Right above your “Start()” function, make sure you declare the function you want to call by adding
“[DllImport(“__Internal”)]
private static extern void Speak(string str);”
4: That’s it, now you can call ” Speak(“Text you want to speak”);” function anywhere inside Start, Update, FixedUpdate, etc…
The Example C# file would be like this.
using UnityEngine;
using System.Runtime.InteropServices;
public class NewBehaviourScript : MonoBehaviour {
[DllImport(“__Internal”)]
private static extern void Speak(string str);
void Start() {
Speak(“Text you want to speak.”);
}
}
There you go, we just saved you a few $$ by above code. If you have any of such cool stuff to do in Unity, connect with me. I and my team will be glad to help you and your team.