Audio loading with XMLHttpRequest in JavaScript - javascript

I am learing Web Audio API. Im having a problem in loading my sound file thourgh XMLHttpRequest in JavaScript. Kindly please help.Here is my code
var source;
function start() {
console.log("WELCOME!!");
try{
var actx = new AudioContext();
}catch(e){
console.log('WebAudio api is not supported!!');
}
source = actx.createBufferSource()
var req = new XMLHttpRequest();
req.open('GET','src3.ogg',true);
req.responseType='ArrayBuffer';
req.onload = function(){
var audioData = req.response;
actx.decodeAudioData(audioData,function(buffer){
source.buffer = buffer;
source.connect(actx.destination);
source.loop();
},
function(e){
console.log('Error in decoding audio'+e.err);
}
);
}
req.send();
}
function play() {
source.start(0);
}
function stop(){
source.stop(0);
}
Browser is showing this error this:
XML Parsing Error: not well-formed
Location: file:///home/uzumaki/Web_Audio_Projects/src3.ogg
Line Number 1, Column 5:
And start() method is called on the onload event of body tag

Substitute
req.responseType = "arraybuffer";
for
req.responseType = "ArrayBuffer";
.responseType is not converted to lowercase by XMLHttpResponse instance

Related

Use xhr.overrideMimeType but get server response first?

I want to get a Base64 encoded file from the server in order to use it in a dataURL so I use:
xhr.overrideMimeType("text/plain; charset=x-user-defined");
So I get the unprocessed data to perform the base64 encoding on.
But I also want to get the mimetype originally returned from the server to declare my dataURL:
var dataUrl = 'data:'+mimetype+';base64,'+b64;
when I try something like the following:
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
var mimetype = xhr.getResponseHeader('content-type');
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.send(null);
the content-type returned is always null
Full source:
function getFileDataUrl(link,mimetype)
{
var url = location.origin+link;
var getBinary = function (url)
{
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
if(mimetype == null)
{
mimetype = xhr.getResponseHeader('content-type');
console.log('mimetype='+mimetype);
}
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.send(null);
return xhr.responseText;
};
var bin = getBinary(url);
var b64 = base64Encode(bin);
var dataUrl = 'data:'+mimetype+';base64,'+b64;
return dataUrl;
}
var dataUrl = getFileDataUrl(link,null);
You can set responseType of XMLHttpRequest to "blob" or "arraybuffer" then use FileReader, FileReader.prototype.readAsDataURL() on response. Though note, onload event of FileReader returns results asynchronously. To read file synchronously you can use Worker and FileReaderSync()
var reader = new FileReader();
reader.onload = function() {
// do stuff with `reader.result`
console.log(reader.result);
}
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function() {
reader.readAsDataURL(xhr.response);
}
xhr.send(null);
At chromium synchronous XMLHttpRequest() is deprecated, see https://xhr.spec.whatwg.org/.
You can use Promise at main thread to get data URI of requested resource using either Worker or when FileReader load event is dispatched. Or use synchronous XMLHttpRequest() and FileReaderSync() at Worker thread, then listen for message event at main thread, use .then() to get Promise value.
Main thread
var worker = new Worker("worker.js");
var url = "path/to/resource";
function getFileDataUrl(url) {
return new Promise(function(resolve, reject) {
worker.addEventListener("message", function(e) {
resolve(e.data)
});
worker.postMessage(url);
})
}
getFileDataUrl(url)
.then(function(data) {
console.log(data)
}, function(err) {
console.log(err)
});
worker.js
var reader = new FileReaderSync();
var request = new XMLHttpRequest();
self.addEventListener("message", function(e) {
var reader = new FileReaderSync();
request.open("GET", e.data, false);
request.responseType = "blob";
request.send(null);
self.postMessage(reader.readAsDataURL(request.response));
});
plnkr http://plnkr.co/edit/gayWpkTVydmKYMnPr3jD?p=preview

Can I create a growing file source URL which is not a video/audio Type?

I have read this article, but this is a video's solution.
Now, I want create a non vidoe/audio sourceBuffer url. I don't know how to implement it. I think that maybe mediasource is not support.
<script>
var ms = new MediaSource();
var src = window.URL.createObjectURL(ms);
console.log(src);
// sourceopen is not work.
// I don't know if i can create a non audio/video type growing file url?
ms.addEventListener('sourceopen', function(e) {
var sourceBuffer = ms.addSourceBuffer('application/octet-stream');
var xhr = new XMLHttpRequest();
xhr.open('GET', '/test.bin', true); // just a binary content
xhr.responseType = 'arraybuffer';
xhr.send();
xhr.onload = function() {
if (xhr.status >= 400) {
alert('Unexpected status code ' + xhr.status);
return false;
}
sourceBuffer.appendBuffer(xhr.response);
};
}, false);
</script>

Basic Web Audio API not playing a mp3 file?

I'm trying to follow a tutorial online by piecing together the examples. I feel like this should be playing the mp3 file. I'm using the Chrome browser and it's up to date. I don't get any errors on the console. I'm not sure what I need to change or add to make this work.
<script type="text/javascript">
//creating an audio context
window.addEventListener('load',init);
function init()
{
try
{
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context=new AudioContext();
}
catch(e)
{
alert("Your browser doesn't support Web Audio API");
}
loadSound();
playSound();
}
//loading sound into the created audio context
function loadSound()
{
//set the audio file's URL
var audioURL='audio files/song.mp3';
//creating a new request
var request = new XMLhttpRequest();
request.open("GET",audioURL,true);
request.responseType= 'arraybuffer';
request.onLoad funtion(){
//take the audio from http request and decode it in an audio buffer
var audioBuffer = null;
context.decodeAudioData(request.response, function(buffer){ audioBuffer= buffer;});
}
request.send();
}, onError);
//playing the audio file
function playSound(buffer) {
//creating source node
var source = audioContext.createBufferSource();
//passing in file
source.buffer = audioBuffer;
//start playing
source.start(0);
}
</script>
</head>
</html>
You are using async XMLHttpRequest (note that it should be spelled by capital "H"), so most probably playSound function is called before request.onLoad (note: missing =) completes.
Try to trace execution of your script using console.log or similar to find bugs like this and use JavaScript Console to catch syntax errors.
i got this thing fixed :) i made use of audio tag along with web audio API. here's the code :
var audio = new Audio();
audio.src = 'audio files/song.mp3';
audio.controls = true;
audio.autoplay = true;
document.body.appendChild(audio);
var context = new webkitAudioContext();
var analyser = context.createAnalyser();
window.addEventListener('load', function(e) {
// Our <audio> element will be the audio source.
var source = context.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(context.destination);
}, false);
thnks for trying to help :))
Is your audioURL correct?
audio files/song.mp3 Why is there an empty space?
============Edit============
<script>
//creating an audio context
var context;
var audioBuffer;
window.addEventListener('load', init);
function init()
{
try
{
window.AudioContext = window.AudioContext || window.webkitAudioContext;
context=new AudioContext();
}
catch(e)
{
alert("Your browser doesn't support Web Audio API");
}
loadSound();
// playSound(); // comment here
}
//loading sound into the created audio context
function loadSound()
{
// set the audio file's URL
var audioURL='AllofMe.mp3';
//creating a new request
var request = new XMLHttpRequest();
request.open("GET",audioURL,true);
request.responseType= 'arraybuffer';
request.onload = function(){
//take the audio from http request and decode it in an audio buffer
context.decodeAudioData(request.response, function(buffer){
audioBuffer = buffer;
console.log(audioBuffer);
if(audioBuffer){ // check here
playSound();
}
});
};
request.send();
}
//playing the audio file
function playSound() {
//creating source node
var source = context.createBufferSource();
//passing in file
source.buffer = audioBuffer;
//start playing
source.connect(context.destination); // added
source.start(0);
console.log('playing');
}
</script>
I was looking for the solution to play mp3 on a mobile device, and found this page, I've made provided example to work with a help from here. Providing working example below:
var context;
var saved;
try {
context = new (window.AudioContext || window.webkitAudioContext)();
}
catch (e) {
console.log("Your browser doesn't support Web Audio API");
}
if (saved) {
playSound(saved);
} else {
loadSound();
}
//loading sound into the created audio context
function loadSound() {
//set the audio file's URL
var audioURL = '/path/to/file.mp3';
//creating a new request
var request = new XMLHttpRequest();
request.open('GET', audioURL, true);
request.responseType = 'arraybuffer';
request.onload = function () {
//take the audio from http request and decode it in an audio buffer
context.decodeAudioData(request.response, function (buffer) {
// save buffer, to not load again
saved = buffer;
// play sound
playSound(buffer);
});
};
request.send();
}
//playing the audio file
function playSound(buffer) {
//creating source node
var source = context.createBufferSource();
//passing in data
source.buffer = buffer;
//giving the source which sound to play
source.connect(context.destination);
//start playing
source.start(0);
}
It looks like playing files works fine on Android device, but not iOS. For that you have to follow this guide: How to: Web Audio on iOS (but use touchend event and replace noteOn method to start).

Show video blob after reading it through AJAX

While I was trying to create a workaround for Chrome unsupporting blobs in IndexedDB I discovered that I could read an image through AJAX as an arraybuffer, store it in IndexedDB, extract it, convert it to a blob and then show it in an element using the following code:
var xhr = new XMLHttpRequest(),newphoto;
xhr.open("GET", "photo1.jpg", true);
xhr.responseType = "arraybuffer";
xhr.addEventListener("load", function () {
if (xhr.status === 200) {
newphoto = xhr.response;
/* store "newphoto" in IndexedDB */
...
}
}
document.getElementById("show_image").onclick=function() {
var store = db.transaction("files", "readonly").objectStore("files").get("image1");
store.onsuccess = function() {
var URL = window.URL || window.webkitURL;
var oMyBlob = new Blob([store.result.image], { "type" : "image\/jpg" });
var docURL = URL.createObjectURL(oMyBlob);
var elImage = document.getElementById("photo");
elImage.setAttribute("src", docURL);
URL.revokeObjectURL(docURL);
}
}
This code works fine. But if I try the same process, but this time loading a video (.mp4) I can't show it:
...
var oMyBlob = new Blob([store.result.image], { "type" : "video\/mp4" });
var docURL = URL.createObjectURL(oMyBlob);
var elVideo = document.getElementById("showvideo");
elVideo.setAttribute("src", docURL);
...
<video id="showvideo" controls ></video>
...
Even if I use xhr.responseType = "blob" and not storing the blob in IndexedDB but trying to show it immediately after loading it, it still does not works!
xhr.responseType = "blob";
xhr.addEventListener("load", function () {
if (xhr.status === 200) {
newvideo = xhr.response;
var docURL = URL.createObjectURL(newvideo);
var elVideo = document.getElementById("showvideo");
elVideo.setAttribute("src", docURL);
URL.revokeObjectURL(docURL);
}
}
The next step was trying to do the same thing for PDF files, but I'm stuck with video files!
This is a filler answer (resolved via the OP found in his comments) to prevent the question from continuing to show up under "unanswered" questions.
From the author:
OK, I solved the problem adding an event that waits for the
video/image to load before executing the revokeObjectURL method:
var elImage = document.getElementById("photo");
elImage.addEventListener("load", function (evt) { URL.revokeObjectURL(docURL); }
elImage.setAttribute("src", docURL);
I suppose the revokeObjectURL method was executing before the video
was totally loaded.

Can't pass a DOM element to a constructor function in Javascript when trying to abstract section of WebAudio API xhr request

My problem is this. When I add an argument to the audioBoing function below and then place the same argument in the getElementById string, the function doesn't work. I get an error that says uncaught type error, cannot call method 'AddEventListener' of null
The function below works fine. I rewrote the function below it to reflect what I'm trying to do. Ultimately I am trying to abstract a good portion of the function so I can just plug in arguments and run it without having to rewrite it each time for each sound it stores / launches.
var playAudioFileOneDrumOneBig = function () {
var source = context.createBufferSource();
source.buffer = savedBufferOne;
source.connect(delay.input);
delay.connect(convolver.input);
convolver.connect(context.destination);
source.noteOn(0); // Play sound immediately
};
function audioBoing()
var xhr = new XMLHttpRequest();
xhr.open('get', 'audio/F.mp3', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
context.decodeAudioData(xhr.response,
function(incomingBuffer1) {
savedBufferOne = incomingBuffer1;
var noteOneDrumOneBig = document.getElementById("noteOneDrumOneBig");
noteOneDrumOneBig.addEventListener("click", playAudioFileOneDrumOneBig , false);
}
);
};
xhr.send();
};
audioBoing();
ReWritten non-working
function audioBoing(yay) { //added yay
this.yay=yay; // defined yay
var xhr = new XMLHttpRequest();
xhr.open('get', 'audio/F.mp3', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
context.decodeAudioData(xhr.response,
function(incomingBuffer1) {
savedBufferOne = incomingBuffer1;
var noteOneDrumOneBig = document.getElementById(yay); //passed yay
noteOneDrumOneBig.addEventListener("click", playAudioFileOneDrumOneBig , false); //error happens here
}
);
};
xhr.send();
};
audioBoing(noteOneDrumOneBig);
You didn't quote the string you passed to audioBoing
audioBoing("noteOneDrumOneBig");

Categories