UNPKG

ai-code-writer

Version:

An AI code writer application using OpenAI APIs for audio transcription and chat completion.

97 lines (96 loc) 3.71 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const node_web_audio_api_1 = require("node-web-audio-api"); class NodeMp3Player { constructor() { this.gainNode = null; this.sourceNode = null; this.audioContext = new node_web_audio_api_1.AudioContext(); this.endCallback = () => false; } get onended() { return this.sourceNode.onended; } set onended(callback) { this.endCallback = callback; } get src() { return this.buffer; } set src(buffer) { void this.cleanAudio(); this.audioContext = new node_web_audio_api_1.AudioContext(); this.gainNode = null; this.buffer = buffer; } play() { return __awaiter(this, void 0, void 0, function* () { if (!this.buffer) { return; } const audioBuffer = yield this.getBuffer(); if (!audioBuffer) return; if (this.gainNode) this.gainNode.disconnect(); this.gainNode = new node_web_audio_api_1.GainNode(this.audioContext, { gain: 1 }); this.gainNode.connect(this.audioContext.destination); const source = this.audioContext.createBufferSource(); this.sourceNode = source; source.buffer = audioBuffer; source.connect(this.gainNode); source.start(this.audioContext.currentTime); // source.stop(this.audioContext.currentTime + audioBuffer.duration); yield new Promise((resolve) => { source.onended = (_) => resolve(); }); yield this.cleanAudio(); this.endCallback(); }); } stop() { return __awaiter(this, void 0, void 0, function* () { if (!this.sourceNode) return; this.sourceNode.stop(this.audioContext.currentTime); yield this.cleanAudio(); }); } cleanAudio() { return __awaiter(this, void 0, void 0, function* () { if (this.sourceNode) this.sourceNode.disconnect(); this.sourceNode = null; if (this.gainNode) this.gainNode.disconnect(); this.gainNode = null; yield this.audioContext.close(); }); } getBuffer() { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => { if (!this.buffer) { resolve(null); return; } this.audioContext.decodeAudioData(this.buffer.buffer.slice(this.buffer.byteOffset, this.buffer.byteOffset + this.buffer.byteLength), (audioBuffer) => { resolve(audioBuffer); }, (err) => { console.log(err.message); resolve(null); }); }); }); } } exports.default = NodeMp3Player;