'use strict';
var contentType = require('./content-type');
function getContentType(file) {
return new Promise(function (resolve, reject) {
var blobToText = new Blob([file]).slice(0, 4);
var r = new FileReader();
r.readAsText(blobToText);
r.onload = function () {
var ct = contentType(r.result);
if (ct) {
resolve(ct);
} else {
var err = new Error('Unable to determine content type from file header; only wav, flac, and ogg/opus are supported.');
err.name = 'UNRECOGNIZED_FORMAT';
reject(err)
}
};
});
}
/**
* Plays audio from File/Blob instances
* @param file
* @param contentType
* @constructor
*/
function FilePlayer(file, contentType) {
var audio = this.audio = new Audio();
if (audio.canPlayType(contentType)) {
audio.src = URL.createObjectURL(new Blob([file], {type: contentType}));
audio.play();
} else {
// if we emit an error, it prevents the promise from returning the actual result
// however, most browsers do not support flac, so this is a reasonably scenario
var err = new Error('Current browser is unable to play back ' + contentType);
err.name = 'UNSUPPORTED_FORMAT';
err.contentType = contentType;
throw err;
}
this.stop = function stop() {
audio.pause();
audio.currentTime = 0;
}
}
function playFile(file) {
return getContentType(file).then(function (contentType) {
return new FilePlayer(file, contentType);
});
}
module.exports = FilePlayer;
module.exports.getContentType = getContentType;
module.exports.playFile = playFile;