Reputation: 331
I am using php for server side scripting. In default I am using "audio" tag for playing audio files, Because my api call returns file path so it is easily handle. for example my example look like this:
{
'id':123,
'question':'tell about your self?',
'audio':'/wdk/path/00fl.mp3'
}
so i can easily use this in audio tag.<audio src="www.abc.in/wdk/path/00fl.mp3" preload="auto">
But now i getting different format of API response. It returns data content instead of url. For example
{
'id':123,
'question':'tell about your self?',
'audio':'/wdk/path/MP3'
}
so now i need to make curl call again with content-type:audio/mpeg for getting data-content.It returns raw mp3 format data. So how can we play the audio file in browser? is any player there for convert mp3 format data to player data straightly? and i tried another way, but i could not able to store a mp3 format file in php. can we create mp3 file using php? for ex:
$myfile = fopen("D:\xampp\htdocs\abc\testfile.mp3", "w");
$fwrite($myfile, $result);
my curl response like this:
ID3#TSSELavf56.15.102��8�Infora
!#%*,.0357<>@BEGIMPRTVY[adfhjmqsuxz|~��������������������������������������������������Lavc56.13$a5Cwc��8�"#�p7I<��Z���<ѣF�
��HP���.uN{P�! �{�����������]�D�DDwww��������"'����_���";�������=��B""�������
Upvotes: 1
Views: 3345
Reputation:
You could use data-URIs as @n-dru suggests in his answer, but you should be aware of a couple of things:
A better approach IMO, is to use Blobs and ObjectURLs. It's not without its own drawbacks though:
The advantage is that the data can be loaded and used as a raw byte-buffer with no overhead in decoding nor bandwidth.
This example loads the MP3 data (which would be the raw data you receive), then creates a Blob and an ObjectURL for the Blob. This can then be set as source for the audio element.
The example also shows how to handle the asynchronous nature of the various stages.
var audio = document.getElementById("audio");
audio.onload = function() {
// audio has loaded..
audio.play();
// continue from here (or the onerror event, not shown)
};
// load the url as raw data and create an ObjectURL:
loadRaw("/wdk/path/MP3", function(url) {
audio.src = url;
});
function loadRaw(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "arraybuffer";
xhr.onerror = function() {console.log("Network error.")};
xhr.onload = function() {
if (xhr.status === 200) {
var blob = new Blob([xhr.response], {type: "audio/mpeg"}),
oURL = (URL || webkitURL).createObjectURL(blob);
callback(oURL);
}
else {console.log("Loading error:" + xhr.statusText)}
};
xhr.send();
}
Upvotes: 1
Reputation: 9420
If you are getting the contents of the mp3 file, you can use data URI, the source is just encoded file contents:
echo '<audio src="data:audio/mpeg;base64,'.base64_encode($sound_text).'" autoplay="autoplay" controls ></audio>';
Upvotes: 2