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. How I need to continue the script in order to play the second sentence from the audio/audio_02.mp3? Thanks in advance from Hungary.
<!DOCTYPE html>
<html lang="en">
<head>
<title>ENGLISH HOMONYMS</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script type="text/javascript">
function play() {
var audio = new Audio('audio/audio_01.mp3');
audio.play();
}
</script>
<h2>ENGLISH HOMONYMS</h2>
<p onclick= "play();">The bandage was wound around the wound.</p>
<p onclick= "play();">farm was used to produce produce.</p>
</body>
</html>
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 class="words">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>
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();
}
.play-music:hover {
background-color: black;
color: white;
}
<p class="play-music" onclick="play()">...</p>
<html>
<body>
<script>
function play() {
var audio = new Audio('http://codeskulptor-demos.commondatastorage.googleapis.com/descent/spring.mp3');
audio.play();
}
</script>
<p onclick="play()">...</p>
</style>
</body>
</html>
As regular HTML and not separated for the animated one:
<html>
<body>
<script>
function play() {
var audio = new Audio('http://codeskulptor-demos.commondatastorage.googleapis.com/descent/spring.mp3');
audio.play();
}
</script>
<p class="play-music" onclick="play()">...</p>
<style>
.play-music:hover {
background-color: black;
color: white;
}
</style>
</body>
</html>
Hope you'll find it useful.