How to stop audio in an iframe using web audio api after hiding its container div?

浪子不回头ぞ 提交于 2019-12-11 08:07:09

问题


I have an iframe where users can play/stop audio (using web audio api). But how can I stop audio if I hide that iframe? (e.g., by setting the CSS property containerDiv.css('display', 'none')). I've tried to clear the parent div with containerDiv.html(''), but audio inside iframe still keeps playing.


回答1:


You can use the postMessage API to communicate with the iframe. This would allow you to send a message to the iframe telling it to stop the audio.

A script in the parent window:

// Assuming the origin of your iframe is http://example.org
function hideTetrisIframe(){
  var iframe = document.getElementById('tetris');
  iframe.style.display = 'none';
  iframe.contentWindow.postMessage('stop', 'http://example.org'); 
}

A script inside the iframe:

window.addEventListener('message', function(event) {
  if (event.data === 'stop') {
    // Stop audio that's playing
  }
}, false);


来源:https://stackoverflow.com/questions/23687635/how-to-stop-audio-in-an-iframe-using-web-audio-api-after-hiding-its-container-di

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!