web programming – Problem with web audio API in google chrome

Question:

There is some code that works fine in Firefox, but somehow doesn't work in chrome (no sound). What could be the problem?

$(document).ready(function() {
  var audio = new Audio('audio');
  audio.toggle();

  $(document).keydown(function(e) {
    //Space
    if (e.keyCode == 32) {
      audio.toggle();
    }
  });
});

function Audio(id) {
  var that = this;
  this.elem = document.getElementById(id);
  this.playing = false;

  var AudioContext = window.AudioContext || window.webkitAudioContext;
  var ctx = new AudioContext;
  var source = ctx.createMediaElementSource(this.elem);
  var dest = ctx.destination;
  var gain = ctx.createGain();


  source.connect(gain);
  gain.connect(dest);


  this.toggle = function() {
    if (that.playing) {
      that.elem.pause();
    } else {
      that.elem.play();
    }
    that.playing = !that.playing;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <link rel='stylesheet' href='main.css' />
  <title>Web audio API</title>
</head>

<body>
  <audio src="someSong.mp3" id="audio"></audio>

</body>

</html>

Answer:

For Chrome, Yandex and Opera, you need a secure connection (https: //) otherwise it does not give access to the microphone

Scroll to Top