territorium-microphone
Version:
Componente de prueba
325 lines (280 loc) • 9.93 kB
JavaScript
'use strict';var vue=require('vue');function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]);
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}var __default__ = /*#__PURE__*/vue.defineComponent({
name: 'TerritoriumMicrophone',
// vue component name
props: {
width: {
type: [Number, String],
default: "50px"
},
height: {
type: [Number, String],
default: '20px'
},
lineWidth: {
type: [Number, String],
default: '5'
}
},
data: function data() {
return {
canvasCtx: null,
canvas: null,
audioCtx: null,
analyser: null,
dataArray: null,
bufferLength: null,
mediaRecorder: null,
stream: null,
chunks: [],
source: null,
audioURL: null,
audioFormat: "audio/webm"
};
},
methods: {
startRecord: function startRecord() {
this.mediaRecorder.start();
},
stopRecord: function stopRecord() {
if (this.mediaRecorder.state == 'recording') {
this.mediaRecorder.stop(); // this.stream.getTracks().forEach(track => track.stop());
// mediaRecorder.requestData();
}
},
draw: function draw() {
var WIDTH = this.canvas.width;
var HEIGHT = this.canvas.height;
requestAnimationFrame(this.draw);
this.analyser.getByteTimeDomainData(this.dataArray);
this.canvasCtx.fillStyle = 'rgb(200, 200, 200)';
this.canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
this.canvasCtx.lineWidth = this.lineWidth;
this.canvasCtx.strokeStyle = 'rgb(0, 0, 0)';
this.canvasCtx.beginPath();
var sliceWidth = WIDTH * 1.0 / this.bufferLength;
var x = 0;
for (var i = 0; i < this.bufferLength; i++) {
var v = this.dataArray[i] / 128.0;
var y = v * HEIGHT / 2;
if (i === 0) {
this.canvasCtx.moveTo(x, y);
} else {
this.canvasCtx.lineTo(x, y);
}
x += sliceWidth;
}
this.canvasCtx.lineTo(this.canvas.width, this.canvas.height / 2);
this.canvasCtx.stroke();
},
visualize: function visualize() {
if (!this.audioCtx) {
this.audioCtx = new AudioContext();
}
this.source = this.audioCtx.createMediaStreamSource(this.stream);
this.analyser = this.audioCtx.createAnalyser();
this.analyser.fftSize = 2048;
this.bufferLength = this.analyser.frequencyBinCount;
this.dataArray = new Uint8Array(this.bufferLength);
this.source.connect(this.analyser);
this.draw();
},
readAudioURL: function readAudioURL(blob) {
return new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function () {
resolve(reader.result);
};
reader.onerror = reject;
});
},
mediaRecorderOnStop: function mediaRecorderOnStop(e) {
var _this = this;
return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
var blob;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
console.log('mediaRecorderOnStop send-url-audio this.chunks 1', _this.chunks);
blob = new Blob(_this.chunks, {
'type': _this.audioFormat
});
_this.chunks = []; // this.audioURL = await this.readAudioURL(blob);
// this.$emit('send-url-audio', this.audioURL);
_this.$emit('send-url-audio', blob);
console.log('mediaRecorderOnStop send-url-audio', blob);
console.log('mediaRecorderOnStop send-url-audio this.chunks 2', _this.chunks);
case 6:
case "end":
return _context.stop();
}
}
}, _callee);
}))();
},
onDataAvailable: function onDataAvailable(e) {
this.chunks.push(e.data);
},
onError: function onError(err) {
console.log('The following error occured: ' + err);
},
updateStreamMic: function updateStreamMic(stream) {
this.canvasCtx = this.$refs.canvas.getContext("2d");
this.canvas = this.$refs.canvas;
this.stream = stream;
this.mediaRecorder = new MediaRecorder(this.stream);
this.mediaRecorder.onstop = this.mediaRecorderOnStop;
this.mediaRecorder.ondataavailable = this.onDataAvailable;
this.visualize();
},
getAudio: function getAudio(audioFormat) {
this.audioFormat = audioFormat;
this.stopRecord();
this.startRecord();
}
}
});
var __injectCSSVars__ = function __injectCSSVars__() {
vue.useCssVars(function (_ctx) {
return {
"ec09f2b2": _ctx.width,
"c8d25734": _ctx.height
};
});
};
var __setup__ = __default__.setup;
__default__.setup = __setup__ ? function (props, ctx) {
__injectCSSVars__();
return __setup__(props, ctx);
} : __injectCSSVars__;var _withId = /*#__PURE__*/vue.withScopeId("data-v-2bb71b2e");
vue.pushScopeId("data-v-2bb71b2e");
var _hoisted_1 = {
class: "territorium-microphone"
};
var _hoisted_2 = {
class: "visualizer",
ref: "canvas"
};
vue.popScopeId();
var render = /*#__PURE__*/_withId(function (_ctx, _cache, $props, $setup, $data, $options) {
return vue.openBlock(), vue.createBlock("div", _hoisted_1, [vue.createVNode("canvas", _hoisted_2, null, 512)]);
});function styleInject(css, ref) {
if ( ref === void 0 ) ref = {};
var insertAt = ref.insertAt;
if (!css || typeof document === 'undefined') { return; }
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
if (insertAt === 'top') {
if (head.firstChild) {
head.insertBefore(style, head.firstChild);
} else {
head.appendChild(style);
}
} else {
head.appendChild(style);
}
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
}var css_248z = "\n.territorium-microphone[data-v-2bb71b2e] {\n display: flex;\n justify-content: center;\n flex-direction: column;\n text-align: center;\n background-color: aquamarine;\n width: 100%;\n}\n.visualizer[data-v-2bb71b2e]{\n width: var(--ec09f2b2);\n height: var(--c8d25734);\n}\n";
styleInject(css_248z);__default__.render = render;
__default__.__scopeId = "data-v-2bb71b2e";// Import vue component
// IIFE injects install function into component, allowing component
// to be registered via Vue.use() as well as Vue.component(),
var component = /*#__PURE__*/(function () {
// Get component instance
var installable = __default__; // Attach install function executed by Vue.use()
installable.install = function (app) {
app.component('TerritoriumMicrophone', installable);
};
return installable;
})(); // It's possible to expose named exports when writing components that can
// also be used as directives, etc. - eg. import { RollupDemoDirective } from 'rollup-demo';
// export const RollupDemoDirective = directive;
var namedExports=/*#__PURE__*/Object.freeze({__proto__:null,'default': component});// only expose one global var, with named exports exposed as properties of
// that global var (eg. plugin.namedExport)
Object.entries(namedExports).forEach(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
exportName = _ref2[0],
exported = _ref2[1];
if (exportName !== 'default') component[exportName] = exported;
});module.exports=component;