How to make your browser talk with JavaScript

How to make your browser talk with JavaScript

1. The simplest example

Let's create a basic function that takes the words or phrases we want to say and lets our browser say them. We will make use of the native speechSyntehsis API available on most modern browsers.

function speak(sentence) {
    const utterance = new SpeechSynthesisUtterance(sentence)
    window.speechSynthesis.speak(utterance)
}

//test
speak('hello world');

Believe it or not, the above code is all you need to make most browsers speak a sentence! Let's look at what's happening here.

We created the speak() function which takes a word as a parameter. We create a sound object, which is actually a language request object that contains all the data about what to say and how to say it.

2. Customize speech speed and pitch

Let's make a slightly more complex example and try to modify the speed and pitch of the spoken words.

/**
 * @param sentence: the sentence to be said * @param pitch: pitch, value range (0 - 2) default value: 1
 * @param rate: speaking rate, value range (0.1 - 10) default value: 1
 */
function speak(sentence, pitch, rate) {
    const utterance = new SpeechSynthesisUtterance(sentence)

    utterance.rate = rate
    utterance.pitch = pitch

    window.speechSynthesis.speak(utterance)
}

In the above example, we added two parameters, pitch and speaking speed, based on the original function. After we create the sound object, we can modify certain properties directly on the sound object. However, it cannot currently be modified through constructors or setter methods.

pitch is a floating point number ranging from 0 to 2, with a default value of 1. The effect of this value may be limited by the engine or sound.

rate is a floating point number ranging from 0.1 to 10, and the default value is 1.

Now, if we call the above code with a simple sentence, our browser will speak the following with normal speaking speed and tone:

speak('Hello world', 1, 1)

3. How to adjust the volume

We can also adjust the volume just like we adjust the pitch and tempo. Let’s take a quick look at how to do that.

/**
 * @param sentence: the sentence to be said * @param volume: volume, value range (0 - 1) default value: 0.5
 */
function speak(sentence, volume) {
    const utterance = new SpeechSynthesisUtterance(sentence)

    utterance.volume = volume

    window.speechSynthesis.speak(utterance)
}

Modify the previous code, we now pass in the volume parameter. The volume is also a floating point number, ranging from 0 to 1, and the default value is 0.5.

Likewise, there is currently no way to set the volume via the constructor or setter methods. Now, we can pass the sentence and volume we want to this function and hear the desired result.

4. Commonly used functions

The speechSynthesis object has a few functions that can be useful. We can pause, resume, or even cancel the progress of a language. Let’s take a quick look:

const utterance = new SpeechSynthesisUtterance('Hello world');
window.speechSynthesis.speak(utterance);

// Pause window.speechSynthesis.pause();
// Resume window.speechSynthesis.resume();
// Cancel window.speechSynthesis.cancel();

The above code will say the sentence we want, and the speech will be paused, resumed, and finally cancelled. You can also try the above code in your browser.

We can also directly determine whether the audio is paused through the paused property on the speechSynthesis object, which will return a Boolean value to indicate whether the audio is paused.

window.speechSynthesis.paused // Boolean

What if there are still some backlog of sentences waiting to be read? Well, there is also a property pending, which is used to check if there is any speech waiting to be spoken. It returns a Boolean value indicating whether there is speech pending for processing.

const utterThis = new SpeechSynthesisUtterance('Hello world');
const utterThat = new SpeechSynthesisUtterance('Hello JavaScript');

window.speechSynthesis.speak(utterThis);
window.speechSynthesis.speak(utterThat);
window.speechSynthesis.pending;

When the above code is executed, two voice clips will be queued and they will be played in order. When we get the pending property, this value will return true, because there is a second voice waiting to be played.

Note: If you only have one voice, the pending property will always return false because there is no voice queued to play.

5. Event Monitoring

When we use the SpeechSynthesisUtteranceapi, we can listen to several useful events. Let’s take a look at it together:

const utterance = new SpeechSynthesisUtterance('Hello world')

utterance.addEventListener('start', () => console.log('Utterance start'))
utterance.addEventListener('pause', () => console.log('Utterance paused'))
utterance.addEventListener('resume', () => console.log('Utterance resumed'))
utterance.addEventListener('end', () => console.log('Utterance end'))

window.speechSynthesis.speak(utterance)

6. Conclusion

Hopefully this article is enough to get you started with synthesized speech in your browser! You should now know how to start, stop, and pause speech, as well as adjust the rate, pitch, and volume of speech.

The above is the details of how to use JavaScript to make your browser speak. For more information about JavaScript, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of how to use JS to read text aloud on a web page
  • js imitates WeChat voice playback implementation ideas
  • A brief analysis of how to use JavaScript for speech recognition
  • How to use nodejs to make a beeping sound (system alarm sound)
  • JS web page sound playback code is compatible with various browsers
  • Playing sound when the mouse passes over in Javascript

<<:  Linux system opens ports 3306, 8080, etc. to the outside world, detailed explanation of firewall settings

>>:  Detailed explanation of Mysql communication protocol

Recommend

Step by step guide to build a calendar component with React

Table of contents Business Background Using Techn...

How to implement MySQL master-slave replication based on Docker

Preface MySQL master-slave replication is the bas...

Alibaba Cloud ESC Server Docker Deployment of Single Node Mysql

1. Download the accelerated version of msyql dock...

Share 8 MySQL pitfalls that you have to mention

MySQL is easy to install, fast and has rich funct...

Using Docker Enterprise Edition to build your own private registry server

Docker is really cool, especially because it'...

Analysis of the differences between Iframe and FRAME

1. Use of Iframe tag <br />When it comes to ...

Detailed explanation of nmcli usage in CentOS8

Common nmcli commands based on RHEL8/CentOS8 # Vi...

Web page CSS priority is explained in detail for you

Before talking about CSS priority, we need to und...

Problems installing TensorRT in docker container

Uninstall the installed version on Ubuntu: sudo a...

Detailed explanation of Mencached cache configuration based on Nginx

Introduction Memcached is a distributed caching s...

Ubuntu16.04 builds php5.6 web server environment

Ubuntu 16.04 installs the PHP7.0 environment by d...

Vue encapsulation component upload picture component

This article example shares the specific code of ...

A brief talk on responsive design

1. What is responsive design? Responsive design i...