Home > Mobile >  Click on the text and play the sound - any solution?
Click on the text and play the sound - any solution?

Time:03-20

Dear Stackoverflow community,

I have these sentences on an HTML below. Each sentence has its voice clip in MP3. I want to find the simplest javaScript code for playing the voice clip. I mean if I click on a text of a sentence the voice clip starts to play. I don't want buttons for clicking, but making the text clickable. Please, write me the simplest solution include an example HTML for this project. Thanks in advance from Hungary.

<html>
<head>

</head>
<body>

<h2>ENGLISH HOMONYMS</h2>

<p>The bandage was wound around the wound.</p>
<p>The farm was used to produce produce.</p>
<p>The dump was so full that it had to refuse more refuse.</p>
<p>We must polish the Polish furniture.</p>
<p>He could lead if he would get the lead out.</p>
<p>The soldier decided to desert his dessert in the desert.</p>

</body>
</html>

CodePudding user response:

Even Better Solution:

  let words = document.querySelector('.words');

words.innerHTML = words.innerText.split(' ').map(word => `<span onClick="speak('${word}')" >${word}</span>`).join(' ');

function speak(mes){
var msg = new SpeechSynthesisUtterance();
var voices = window.speechSynthesis.getVoices();
msg.voice = voices[10]; 
msg.volume = 1; // From 0 to 1
msg.rate = 1; // From 0.1 to 10
msg.pitch = 2; // From 0 to 2
msg.text = mes;
msg.lang = 'en';
speechSynthesis.speak(msg);
}
<p >The bandage was wound around the wound.</p>

Better solution :

function speak(mes){
var msg = new SpeechSynthesisUtterance();
var voices = window.speechSynthesis.getVoices();
msg.voice = voices[10]; 
msg.volume = 1; // From 0 to 1
msg.rate = 1; // From 0.1 to 10
msg.pitch = 2; // From 0 to 2
msg.text = mes;
msg.lang = 'en';
speechSynthesis.speak(msg);
}
<h1 onClick="speak('hi')" >
  hi
</h1>

<h2 onClick="speak('How are you')" >
  How are you
</h2>

CodePudding user response:

As written in this question:

var audio = new Audio('audio_file.mp3');
audio.play();

function play() {
  var audio = new Audio('http://codeskulptor-demos.commondatastorage.googleapis.com/descent/spring.mp3');
  audio.play();
}
<p onclick="play()">...</p>

Or if you want some animation to it:

function play() {
  var audio = new Audio('http://codeskulptor-demos.commondatastorage.googleapis.com/descent/spring.mp3');
  audio.play();
}
p:hover {
background-color: black;
color: white;

}
<p onclick="play()">...</p>

Hope you'll find it useful.

  • Related