Tengo varias imágenes con la función onclick para reproducir diferentes fuentes de audio para cada imagen por separado. Sin embargo, también quiero una función de alternar o reproducir / pausar que si hace clic en la misma imagen nuevamente, el audio se detiene.

He intentado incorporar .pause () y la función de alternar, pero no consigo que funcione correctamente. ¿Tienen alguna idea y sugerencia sobre cómo usar la función de pausa y / o alternar en este caso?

Aquí está mi violín

var aAudio = new Audio('a.mp3');
var bAudio = new Audio('b.mp3');
var cAudio = new Audio('c.mp3');

function myAudioFunction(letter) {
  if (letter == 'a') {
    aAudio.play();
  } else if (letter == 'b') {
    bAudio.play();
  } else if (letter == 'c') {
    cAudio.play();
  }
}
<a onclick="myAudioFunction('a')" style="cursor:pointer;" title="Facebook" target="_blank">
  <img src="https://d2fi4ri5dhpqd1.cloudfront.net/public/resources/social-networks-icon-sets/circle-dark-gray/facebook.png" alt="Facebook" width="32" style="outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;clear: both;display: block !important;border: none;height: auto;float: none;max-width: 32px !important">
</a>

<a onclick="myAudioFunction('b')" style="cursor:pointer;" title="Vkontakte" target="_blank">
  <img src="https://d2fi4ri5dhpqd1.cloudfront.net/public/resources/social-networks-icon-sets/circle-dark-gray/vkontakte@2x.png" alt="Vkontakte" title="Vkontakte" width="32" style="outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;clear: both;display: block !important;border: none;height: auto;float: none;max-width: 32px !important"
  />
</a>

<a onclick="myAudioFunction('c')" style="cursor:pointer;" title="Vkontakte" target="_blank">
  <img src="https://d2fi4ri5dhpqd1.cloudfront.net/public/resources/social-networks-icon-sets/circle-dark-gray/vkontakte@2x.png" alt="Vkontakte" title="Vkontakte" width="32" style="outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;clear: both;display: block !important;border: none;height: auto;float: none;max-width: 32px !important"
  />
</a>
1
Falconfdfd 28 oct. 2017 a las 18:05

3 respuestas

La mejor respuesta

Puede usar la propiedad paused combinada con la propiedad currentTime para saber si un elemento de audio debe pausarse o reproducirse cuando se presiona el botón.

function myAudioFunction(letter) {
  var players = {
    a: aAudio,
    b: bAudio,
    c: cAudio
  };

  var player = players[letter];

  if (player.currentTime == 0 || player.paused) {
    player.play();
  } else {
    player.pause();
  }
}
2
James 28 oct. 2017 a las 15:20

¡Hay algunas maneras de hacerlo! Use la propiedad paused

var audiolinks = document.querySelectorAll("a");

//loop over all links | audiolinks is a nodelist without forEach - use Array's forEach
Array.prototype.forEach.call(audiolinks, function(element, index) {
  element.addEventListener("click", function() {
    myAudioFunction(index);
  })
});

var aAudio = new Audio('a.mp3');
var bAudio = new Audio('b.mp3');
var cAudio = new Audio('c.mp3');
var audioPlaying = "|"; //use | to avoid selecting Audio element

function myAudioFunction(index) {
  res = String.fromCharCode(97 + index);
  //select char (a, b, etc.) and use bracket to combine it with audio.
  if (window[audioPlaying + "Audio"]) {
    if (!window[audioPlaying + "Audio"].paused && res == audioPlaying) {
      console.log("pause", audioPlaying);
      window[audioPlaying + "Audio"].pause();
    } else if (!window[audioPlaying + "Audio"].paused && res != audioPlaying) {
      console.log("stop", audioPlaying);
      window[audioPlaying + "Audio"].pause();

      window[audioPlaying + "Audio"].currentTime = 0;
    } else {
      console.log("play", audioPlaying);
      window[audioPlaying + "Audio"].play();
    }

  }

  //if res isn't audioPlaying, start the audio
  if (res != audioPlaying) {
    console.log("play", res);
    window[res + "Audio"].play();
    audioPlaying = res;
  }
}
<a style="cursor:pointer;" title="Facebook" target="_blank">
  <img src="https://d2fi4ri5dhpqd1.cloudfront.net/public/resources/social-networks-icon-sets/circle-dark-gray/facebook.png" alt="Facebook" width="32" style="outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;clear: both;display: block !important;border: none;height: auto;float: none;max-width: 32px !important">
</a>

<a style="cursor:pointer;" title="Vkontakte" target="_blank">
  <img src="https://d2fi4ri5dhpqd1.cloudfront.net/public/resources/social-networks-icon-sets/circle-dark-gray/vkontakte@2x.png" alt="Vkontakte" title="Vkontakte" width="32" style="outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;clear: both;display: block !important;border: none;height: auto;float: none;max-width: 32px !important"
  />
</a>

<a style="cursor:pointer;" title="Vkontakte" target="_blank">
  <img src="https://d2fi4ri5dhpqd1.cloudfront.net/public/resources/social-networks-icon-sets/circle-dark-gray/vkontakte@2x.png" alt="Vkontakte" title="Vkontakte" width="32" style="outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;clear: both;display: block !important;border: none;height: auto;float: none;max-width: 32px !important"
  />
</a>
0
Mouser 28 oct. 2017 a las 15:41

Puede verificar si el audio se está reproduciendo verificando su propiedad paused. También debe verificar si el audio nunca se inició, puede hacerlo utilizando la propiedad currentTime.

Aquí está un ejemplo:

var aAudio = new Audio('a.mp3');
var bAudio = new Audio('b.mp3');
var cAudio = new Audio('c.mp3');

function myAudioFunction(letter) {
  toggleAudio(window[letter+"Audio"]);
}

function toggleAudio(audioElm){
   if(!audioElm.currentTime || audioElm.paused){
       audioElm.play();
   }else{
       audioElm.pause();
   }
}
<a onclick="myAudioFunction('a')" style="cursor:pointer;" title="Facebook" target="_blank">
  <img src="https://d2fi4ri5dhpqd1.cloudfront.net/public/resources/social-networks-icon-sets/circle-dark-gray/facebook.png" alt="Facebook" width="32" style="outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;clear: both;display: block !important;border: none;height: auto;float: none;max-width: 32px !important">
</a>

<a onclick="myAudioFunction('b')" style="cursor:pointer;" title="Vkontakte" target="_blank">
  <img src="https://d2fi4ri5dhpqd1.cloudfront.net/public/resources/social-networks-icon-sets/circle-dark-gray/vkontakte@2x.png" alt="Vkontakte" title="Vkontakte" width="32" style="outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;clear: both;display: block !important;border: none;height: auto;float: none;max-width: 32px !important"
  />
</a>

<a onclick="myAudioFunction('c')" style="cursor:pointer;" title="Vkontakte" target="_blank">
  <img src="https://d2fi4ri5dhpqd1.cloudfront.net/public/resources/social-networks-icon-sets/circle-dark-gray/vkontakte@2x.png" alt="Vkontakte" title="Vkontakte" width="32" style="outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;clear: both;display: block !important;border: none;height: auto;float: none;max-width: 32px !important"
  />
</a>
1
Titus 28 oct. 2017 a las 15:23