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

MySQL graphical management tool Navicat installation steps

Table of contents Preface 1. Arrange the installa...

Xftp download and installation tutorial (graphic tutorial)

If you want to transfer files between Windows and...

Basic knowledge of MySQL learning notes

View Database show databases; Create a database c...

Detailed explanation of Vue slot

1. Function : Allows the parent component to inse...

vsCode generates vue templates with one click

1. Use the shortcut Ctrl + Shift + P to call out ...

Analysis of the principle of Nginx using Lua module to implement WAF

Table of contents 1. Background of WAF 2. What is...

How to use vite to build vue3 application

1. Installation Tip: There is currently no offici...

Webpack file packaging error exception

Before webpack packaging, we must ensure that the...

33 ice and snow fonts recommended for download (personal and commercial)

01 Winter Flakes (Individual only) 02 Snowtop Cap...

3 methods to restore table structure from frm file in mysql [recommended]

When mysql is running normally, it is not difficu...

Web page creation for beginners: Learn to use HTML's hyperlink A tag

The hyperlink a tag represents a link point and i...

MySQL slow query operation example analysis [enable, test, confirm, etc.]

This article describes the MySQL slow query opera...

Detailed explanation of JavaScript stack and copy

Table of contents 1. Definition of stack 2. JS st...

Nginx sample code for implementing dynamic and static separation

In combination with the scenario in this article,...