javascript - Load audio file with PHP and play with JS

966

I am trying to load a wave audio-file with php and play the audio with javascript.

My Javascript code:

var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'php/test.php', true); 
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.onreadystatechange = function(){
  if(xmlhttp.readyState == 4) {
    var audio = new Audio("data:audio/wave;base64," + btoa(unescape(encodeURIComponent(xmlhttp.responseText))));
    audio.play();
  }
}
xmlhttp.send(url);

My PHP code:

<?php
  readfile("test.wav");
?>

Unfortunately it's not working. Any ideas?

116

Answer

Solution:

How about:

var audio = new Audio("data:audio/wav;base64," + escape(btoa(xmlhttp.responseText)))

And you can just point the AJAX request directly to the.wav file.

People are also looking for solutions to the problem: how to kill the session cookie after a period of time in php

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.