Problem when playing sound in an img

0

Greetings, I want to change the src of a label to be able to reproduce a sound depending on the image pressed.

The original code is:

<head>
    <script>
        function EvalSound(soundobj) {
            var thissound= eval("document." soundobj);
            thissound.Play();
        }
    </script>
</head>
<body>
    <embed src="animales/perro.mp3" autostart=false width=0 height=0 name="sound1" enablejavascript="true">
    <img src="play.gif" onClick="EvalSound('sound1')">
</body>

It works but always plays the dog.

I have modified it:

<head>
    <script type="text/javascript">
        function EvalSound(soundobj) {
            document.getElementById("reproductor").src = soundobj;
            var thissound= eval("document." soundobj);
            thissound.Play();
        }
    </script>
</head> 
<body> 
    <embed src="" autostart=false id="reproductor" width=0 height=0 name="sound1" enablejavascript="true">
    <main>
        <div class="" id="midiv"> 
            <img id="leon" src="animales/leon.jpg" onClick="EvalSound('animales/leon.mp3')" alt="León" />
            <img id="Halcon" src="animales/halcon.jpg" onClick="EvalSound('animales/halcon.mp3')" alt="Halcón" />
        </div>
    </main>
</body>

The logic is simple: I pick up the sound path when I call the function and then I change the embed src but it does not work ....

Solution ::

<script type="text/javascript">

            var audio = new Audio();;

            function EvalSound(soundobj) { 
                if(audio.play()){
                 audio.pause();
                 audio = null;
                 audio = new Audio(soundobj);
                 audio.play(); 
                }                
            }
</script>

    <div class="" id="midiv"> 
        <img id="leon" src="animales/leon.jpg"       onClick="EvalSound('animales/leon.mp3')" alt="León"  />
        <img id="Halcon" src="animales/halcon.jpg"   onClick="EvalSound('animales/halcon.mp3')"  alt="Halcón"  />
    </div>
    
asked by EduBw 19.01.2018 в 11:54
source

1 answer

1

Based on this , I made a similar example to what you had using the% tag % co:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <script type="text/javascript">
    function EvalSound(src) {
      document.getElementById("sonido").src = src;
      var audio = document.getElementById("reproductor");
      audio.load();
      audio.play();
    }
  </script>
</head>
<body>
  <audio id="reproductor">
    <source id="sonido" src="" type="audio/mpeg">.
  </audio>
  <div class="" id="midiv">
    <img id="leon" src="animales/leon.jpg" onClick="EvalSound('animales/leon.mp3')" alt="León" />
    <img id="Halcon" src="animales/halcon.jpg" onClick="EvalSound('animales/halcon.mp3')" alt="Halcón" />
  </div>
</body>
    
answered by 19.01.2018 в 13:24