Estimada comunidad de Stackoverflow,
Tengo estas oraciones en un HTML a continuación. Cada frase tiene su clip de voz en MP3. Quiero encontrar el código JavaScript más simple para reproducir el clip de voz. ¿Cómo debo continuar con el guión para reproducir la segunda oración del audio/audio_02.mp3? Gracias de antemano desde Hungría.
<!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>Solución aún mejor:
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>Mejor solución:
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>Como está escrito en esta pregunta :
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>O si quieres algo de animación:
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>Como HTML normal y no separado del animado:
<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>Espero que lo encuentre útil.