Implementing Text-to-Speech and Background Music Playback in Vue3

Text-to-Speech Functionality

A button is created to trigger the text-to-speech functionality. The click event handleSpeakTest() initiates the process.

const handleSpeakTest = ((text) => {
  handleSpeak("China");
});

const handleSpeak = ((text) => {
  speech.text = text;
  speech.lang = "zh-CN";
  speech.volume = 1;
  speech.pitch = 2;
  speech.rate = 1;
  synth.speak(speech);
});

The speech parameters can be customized for different effects:

  • speech.lang: Sets the language of the speech (e.g., en-US, zh-CN)
  • speech.pitch: Controls the tone (0-2, default: 1)
  • speech.rate: Adjusts speaking speed (0.1-10, default: 1)
  • speech.text: Specifies the content to be spoken
  • speech.voice: Chooses the voice used for speech
  • speech.volume: Sets the volume level (0-1, default: 1)

Audio Effects and Background Music

Another button is used to control audio playback. For background music, it's common to start playing automatically when the page loads. However, in this case, the playback is controlled via button clicks to allow play/pause functionality.

In the template:

<el-button type="primary" @click="playMusic">Start Music</el-button>
<el-button type="primary" @click="pauseMusic">Stop Music</el-button>
<audio ref="audioElement" controls style="display: none;">
  <source src="./assets/background.mp3" type="audio/mp3">
</audio>

In the script section:

const audioElement = ref(null);

const playMusic = () => {
  audioElement.value.play();
};

const pauseMusic = () => {
  audioElement.value.pause();
};

Ensure the audio file path is correct. The audio element is hidden using style="display: none;".

Enhanced Background Music Feature — Image Rotation

To indicate that background music is playing, an image can be animated to rotate continuously. This is achieved using CSS animations and an ID selector.

In the template:

<img class="logo_word" id="rotate" alt="music logo" src="./assets/musiclogo.png" @click="toggleMusic" />

In the styles:

/* Rotating image */
#rotate {
  width: 40px;
  height: 40px;
  border-radius: 140px;
  -webkit-animation: spin 6s linear 0s infinite;
}

#rotate:hover {
  -webkit-animation-play-state: paused;
}

@-webkit-keyframes spin {
  from {
    -webkit-transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(360deg);
  }
}

Hovering over the image pauses the rotation. Clicking the image triggers the toggleMusic function, which can be implemented similarly to the previous funcsions to pause the music.

Tags: vue3 text-to-speech audio background-music animation

Posted on Sat, 16 May 2026 17:51:38 +0000 by khayll