Skip to content

Commit

Permalink
add recorder init function
Browse files Browse the repository at this point in the history
  • Loading branch information
streamer45 committed Jul 31, 2019
1 parent bd13dfb commit 19b0ae2
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
8 changes: 8 additions & 0 deletions demo/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,18 @@ const recorder = new Recorder({
workerURL: '/dist/recorder.worker.js',
});

recorder.init().then(() => {
console.log('recorder initialized');
}).catch((err) => {
console.log(err);
});

function start() {
console.log('start');
recorder.start().then(() => {
console.log('recorder started');
}).catch((err) => {
console.log(err);
});
recorder.on('data', (data) => {
const url = URL.createObjectURL(data);
Expand Down
20 changes: 13 additions & 7 deletions src/recorder.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ class Recorder {
this.startTime = 0;
this.stopTime = 0;
this.numSamples = config.numSamples || 4096;
this._startWorker();
}

_startCapture() {
Expand Down Expand Up @@ -49,12 +48,12 @@ class Recorder {
}
}

_startWorker() {
init() {
if (this.worker) return Promise.reject(new Error('recorder already initialized'));
return new Promise((res, rej) => {
const worker = new Worker(this.workerURL);
worker.onmessage = (ev) => {
if (ev.data instanceof Uint8Array) {
console.log('got mp3 data: ' + ev.data.length);
const blob = new Blob([ev.data], {type: 'audio/mpeg'});
const duration = this.stopTime - this.startTime;
this.stopTime = 0;
Expand All @@ -75,6 +74,9 @@ class Recorder {

start() {
if (!this.audioCtx) {
if (!this.worker) {
return Promise.reject(new Error('Worker is not initialized'));
}
const AudioContext = window.AudioContext || window.webkitAudioContext;
if (!AudioContext) {
return Promise.reject(new Error('AudioCtx unsupported'));
Expand Down Expand Up @@ -107,15 +109,19 @@ class Recorder {
this.procNode.disconnect(this.muteNode);
this.muteNode.disconnect(this.audioCtx.destination);
this.mediaStream.getTracks()[0].stop();
//this.audioCtx.close();
//this.audioCtx = null;
this.stopTime = new Date().getTime();
this.mediaStream = null;
this.stopTime = new Date().getTime();
this.worker.postMessage('stop');
}

destroy() {
if (this.worker) this.worker.postMessage('destroy');
if (this.audioCtx) {
this.audioCtx.close();
this.audioCtx = null;
}
if (this.worker) {
this.worker.postMessage('destroy');
}
}

on(event, cb) {
Expand Down

0 comments on commit 19b0ae2

Please sign in to comment.