An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Save recordings as MP3 https://github.com/siyuan-note/siyuan/issues/11727
Daniel8d813eda2331
diff --git a/app/package.json b/app/package.jsonindex 614d718759..087d964219 100644--- a/app/package.json+++ b/app/package.json@@ -53,6 +53,7 @@}],"devDependencies": {+ "@breezystack/lamejs": "1.2.7","@eslint/eslintrc": "^3.3.1","@eslint/js": "^9.24.0","@types/node": "^18.13.0",diff --git a/app/pnpm-lock.yaml b/app/pnpm-lock.yamlindex faa0bfaef5..23cbb64feb 100644--- a/app/pnpm-lock.yaml+++ b/app/pnpm-lock.yaml@@ -18,6 +18,9 @@ importers:specifier: 4.4.2version: 4.4.2devDependencies:+ '@breezystack/lamejs':+ specifier: 1.2.7+ version: 1.2.7'@eslint/eslintrc':specifier: ^3.3.1version: 3.3.5@@ -123,6 +126,9 @@ importers:packages:+ '@breezystack/[email protected]':+ resolution: {integrity: sha512-6wc7ck65ctA75Hq7FYHTtTvGnYs6msgdxiSUICQ+A01nVOWg6rqouZB8IdyteRlfpYYiFovkf67dIeOgWIUzTA==}+'@discoveryjs/[email protected]':resolution: {integrity: sha512-gX9Hx+2BMP5+yXfr4Agb+iBd9YiI729x38wbhfvRSkxQqfXnJUNy1nnyJWetYCvxnL1caWd1HqJnbQwVrgvgeA==}engines: {node: '>=10.0.0'}@@ -3000,6 +3006,8 @@ packages:snapshots:+ '@breezystack/[email protected]': {}+'@discoveryjs/[email protected]': {}'@electron-internal/[email protected]': {}diff --git a/app/src/protyle/breadcrumb/index.ts b/app/src/protyle/breadcrumb/index.tsindex a80db0ecf8..61debc6dc3 100644--- a/app/src/protyle/breadcrumb/index.ts+++ b/app/src/protyle/breadcrumb/index.ts@@ -42,6 +42,10 @@ export class Breadcrumb {private mediaRecorder: RecordMedia;private id: string;private messageId: string;+ private recordUploadMessageIds = new Map<File, string>();+ private pendingRecordFiles = new Set<File>();+ private startingRecord = false;+ private stoppingRecord = false;private previousFocusElement: HTMLElement;private previousRange: Range;@@ -448,18 +452,81 @@ ${padHTML}return items;}- private startRecord(protyle: IProtyle) {+ private async startRecord(protyle: IProtyle, mediaStream: MediaStream) {+ const recorder = new RecordMedia(mediaStream);+ this.mediaRecorder = recorder;+ try {+ await recorder.startRecording();+ } catch (error) {+ recorder.dispose();+ if (this.mediaRecorder === recorder) {+ this.mediaRecorder = undefined;+ }+ throw error;+ }+ recorder.onerror = () => {+ if (this.mediaRecorder !== recorder) {+ return;+ }+ recorder.dispose();+ this.mediaRecorder = undefined;+ hideMessage(this.messageId);+ showMessage(window.siyuan.languages["record-tip"]);+ };this.messageId = showMessage(`<div class="fn__flex fn__flex-wrap"><span class="fn__flex-center">${window.siyuan.languages.recording}</span><span class="fn__space"></span><button class="b3-button b3-button--white">${window.siyuan.languages.endRecord}</button></div>`, -1);document.querySelector(`#message [data-id="${this.messageId}"] button`).addEventListener("click", () => {- this.mediaRecorder.stopRecording();- hideMessage(this.messageId);- const file: File = new File([this.mediaRecorder.buildWavFileBlob()],- `record${(new Date()).getTime()}.wav`, {type: "video/webm"});- uploadFiles(protyle, [file]);+ this.stopRecord(protyle);+ });+ }++ private async stopRecord(protyle: IProtyle) {+ if (this.stoppingRecord || !this.mediaRecorder?.isRecording) {+ return;+ }+ this.stoppingRecord = true;+ const recorder = this.mediaRecorder;+ recorder.onerror = undefined;+ hideMessage(this.messageId);+ try {+ const blob = await recorder.stopRecording();+ const file = new File([blob], `record${Date.now()}.mp3`, {type: "audio/mpeg"});+ this.pendingRecordFiles.add(file);+ this.uploadRecord(protyle, file);+ } catch (error) {+ showMessage(window.siyuan.languages["record-tip"]);+ } finally {+ recorder.dispose();+ if (this.mediaRecorder === recorder) {+ this.mediaRecorder = undefined;+ }+ this.stoppingRecord = false;+ }+ }++ private uploadRecord(protyle: IProtyle, file: File) {+ if (!this.pendingRecordFiles.has(file)) {+ return;+ }+ hideMessage(this.recordUploadMessageIds.get(file));+ this.recordUploadMessageIds.delete(file);+ uploadFiles(protyle, [file], undefined, undefined, (succeeded) => {+ if (!this.pendingRecordFiles.has(file)) {+ return;+ }+ if (succeeded) {+ this.pendingRecordFiles.delete(file);+ return;+ }+ const messageId = showMessage(`<div class="fn__flex fn__flex-wrap">+<span class="fn__flex-center">${window.siyuan.languages.uploadError}</span><span class="fn__space"></span>+<button class="b3-button b3-button--white">${window.siyuan.languages.retry}</button></div>`, -1);+ this.recordUploadMessageIds.set(file, messageId);+ document.querySelector(`#message [data-id="${messageId}"] button`)?.addEventListener("click", () => {+ this.uploadRecord(protyle, file);+ });});- this.mediaRecorder.startRecordingNewWavFile();}private genMobileMenu(protyle: IProtyle) {@@ -578,51 +645,40 @@ ${padHTML}icon: "iconRecord",label: this.mediaRecorder?.isRecording ? window.siyuan.languages.endRecord : window.siyuan.languages.startRecord,click: async () => {- /// #if !BROWSER- if (window.siyuan.config.system.os === "darwin") {- const status = await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "getMicrophone"});- if (["denied", "restricted", "unknown"].includes(status)) {- showMessage(window.siyuan.languages.microphoneDenied);- return;- } else if (status === "not-determined") {- const isAccess = await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "askMicrophone"});- if (!isAccess) {- showMessage(window.siyuan.languages.microphoneNotAccess);- return;- }- }+ if (this.startingRecord || this.stoppingRecord) {+ return;+ }+ if (this.mediaRecorder?.isRecording) {+ this.stopRecord(protyle);+ return;}- /// #endif- if (!this.mediaRecorder) {- navigator.mediaDevices.getUserMedia({audio: true}).then((mediaStream: MediaStream) => {- this.mediaRecorder = new RecordMedia(mediaStream);- this.mediaRecorder.recorder.onaudioprocess = (e: AudioProcessingEvent) => {- // Do nothing if not recording:- if (!this.mediaRecorder.isRecording) {+ this.startingRecord = true;+ let mediaStream: MediaStream;+ try {+ /// #if !BROWSER+ if (window.siyuan.config.system.os === "darwin") {+ const status = await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "getMicrophone"});+ if (["denied", "restricted", "unknown"].includes(status)) {+ showMessage(window.siyuan.languages.microphoneDenied);+ return;+ } else if (status === "not-determined") {+ const isAccess = await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "askMicrophone"});+ if (!isAccess) {+ showMessage(window.siyuan.languages.microphoneNotAccess);return;}- // Copy the data from the input buffers;- const left = e.inputBuffer.getChannelData(0);- const right = e.inputBuffer.getChannelData(1);- this.mediaRecorder.cloneChannelData(left, right);- };- this.startRecord(protyle);- }).catch(() => {- showMessage(window.siyuan.languages["record-tip"]);- });- return;- }+ }+ }+ /// #endif- if (this.mediaRecorder.isRecording) {- this.mediaRecorder.stopRecording();- hideMessage(this.messageId);- const file: File = new File([this.mediaRecorder.buildWavFileBlob()],- `record${(new Date()).getTime()}.wav`, {type: "video/webm"});- uploadFiles(protyle, [file]);- } else {- hideMessage(this.messageId);- this.startRecord(protyle);+ mediaStream = await navigator.mediaDevices.getUserMedia({audio: true});+ await this.startRecord(protyle, mediaStream);+ } catch (error) {+ mediaStream?.getTracks().forEach((track) => track.stop());+ showMessage(window.siyuan.languages["record-tip"]);+ } finally {+ this.startingRecord = false;}}}).element);diff --git a/app/src/protyle/upload/index.ts b/app/src/protyle/upload/index.tsindex 09d196522d..c74d82a450 100644--- a/app/src/protyle/upload/index.ts+++ b/app/src/protyle/upload/index.ts@@ -299,7 +299,8 @@ export const uploadLocalFiles = (files: ILocalFiles[], protyle: IProtyle, isUplo});};-export const uploadFiles = (protyle: IProtyle, files: FileList | DataTransferItemList | File[], element?: HTMLInputElement, successCB?: (res: string) => void) => {+export const uploadFiles = (protyle: IProtyle, files: FileList | DataTransferItemList | File[], element?: HTMLInputElement,+ successCB?: (res: string) => void, completeCB?: (succeeded: boolean) => void) => {// FileList | DataTransferItemList | File[] => File[]let fileList = [];for (let i = 0; i < files.length; i++) {@@ -319,8 +320,10 @@ export const uploadFiles = (protyle: IProtyle, files: FileList | DataTransferIteconst isValidate = protyle.options.upload.handler(fileList);if (typeof isValidate === "string") {showMessage(isValidate);+ completeCB?.(false);return;}+ completeCB?.(true);return;}@@ -329,6 +332,7 @@ export const uploadFiles = (protyle: IProtyle, files: FileList | DataTransferIteelement.value = "";}showMessage("please config: options.upload.url");+ completeCB?.(false);return;}@@ -350,6 +354,7 @@ export const uploadFiles = (protyle: IProtyle, files: FileList | DataTransferIteif (element) {element.value = "";}+ completeCB?.(false);return;}@@ -388,6 +393,7 @@ export const uploadFiles = (protyle: IProtyle, files: FileList | DataTransferIteif (!document.body.contains(protyle.element)) {// 网络较慢时,页签已经关闭destroy(protyle);+ completeCB?.(false);return;}if (xhr.status === 200) {@@ -403,14 +409,28 @@ export const uploadFiles = (protyle: IProtyle, files: FileList | DataTransferIte}genUploadedLabel(responseText, protyle);}+ let succeeded = true;+ try {+ const response = JSON.parse(xhr.responseText);+ if (response.data?.succMap) {+ succeeded = validateResult.files.every((file) => response.data.succMap[file.name]);+ } else if (typeof response.code === "number") {+ succeeded = response.code === 0;+ }+ } catch (error) {+ // 自定义上传接口不一定返回 JSON,HTTP 200 仍视为成功。+ }+ completeCB?.(succeeded);} else if (xhr.status === 0) {showMessage(window.siyuan.languages["_kernel"][28]);+ completeCB?.(false);} else {if (protyle.options.upload.error) {protyle.options.upload.error(xhr.responseText);} else {showMessage(xhr.responseText);}+ completeCB?.(false);}if (element) {element.value = "";@@ -430,5 +450,6 @@ export const uploadFiles = (protyle: IProtyle, files: FileList | DataTransferItexhr.send(formData);}, () => {hideMessage(validateResult.msgId);+ completeCB?.(false);});};diff --git a/app/src/protyle/util/RecordMedia.ts b/app/src/protyle/util/RecordMedia.tsindex e4c4851c0d..25568a880c 100644--- a/app/src/protyle/util/RecordMedia.ts+++ b/app/src/protyle/util/RecordMedia.ts@@ -1,170 +1,139 @@+const SAMPLE_RATE = 44100;+const MP3_BIT_RATE = 96;+const BUFFER_SIZE = 2048;++type EncoderMessage =+ { type: "ready" } |+ { type: "chunk", buffer: ArrayBuffer } |+ { type: "finished" } |+ { type: "error", message: string };+export class RecordMedia {- public SAMPLE_RATE = 44100;- public DEFAULT_SAMPLE_RATE: number;public isRecording = false;- public readyFlag = false;- public leftChannel: Float32List[] = [];- public rightChannel: Float32List[] = [];- public recordingLength = 0;- // This needs to be public so the 'onaudioprocess' event handler can be defined externally.- public recorder: ScriptProcessorNode;-- constructor(e: MediaStream) {- let context;- // creates the audio context- if (typeof AudioContext !== "undefined") {- context = new AudioContext();- } else if (webkitAudioContext) {- context = new webkitAudioContext();- } else {- return;+ public onerror?: (error: Error) => void;++ private readonly context: AudioContext;+ private readonly mediaStream: MediaStream;+ private readonly audioInput: MediaStreamAudioSourceNode;+ private readonly recorder: ScriptProcessorNode;+ private worker: Worker;+ private chunks: ArrayBuffer[] = [];+ private readyPromise: Promise<void>;+ private resolveReady: () => void;+ private rejectReady: (error: Error) => void;+ private stopPromise: Promise<Blob>;+ private resolveStop: (blob: Blob) => void;+ private rejectStop: (error: Error) => void;+ private disposed = false;++ constructor(mediaStream: MediaStream) {+ this.mediaStream = mediaStream;+ const AudioContextConstructor = typeof AudioContext !== "undefined" ? AudioContext : webkitAudioContext;+ if (!AudioContextConstructor) {+ throw new Error("AudioContext is not supported");}- this.DEFAULT_SAMPLE_RATE = context.sampleRate;-- // creates a gain node- const volume = context.createGain();-- // creates an audio node from the microphone incoming stream- const audioInput = context.createMediaStreamSource(e);-- // connect the stream to the gain node- audioInput.connect(volume);-- /* From the spec: The size of the buffer controls how frequently the audioprocess event is- dispatched and how many sample-frames need to be processed each call.- Lower values for buffer size will result in a lower (better) latency.- Higher values will be necessary to avoid audio breakup and glitches */- this.recorder = context.createScriptProcessor(2048, 2, 1);-- // The onaudioprocess event needs to be defined externally, so make sure it is not set:- this.recorder.onaudioprocess = null;-- // we connect the recorder- volume.connect(this.recorder);- this.recorder.connect(context.destination);- this.readyFlag = true;- }-- // Publicly accessible methods:- public cloneChannelData(leftChannelData: Float32List, rightChannelData: Float32List) {- this.leftChannel.push(new Float32Array(leftChannelData));- this.rightChannel.push(new Float32Array(rightChannelData));- this.recordingLength += 2048;+ this.context = new AudioContextConstructor({sampleRate: SAMPLE_RATE});+ this.audioInput = this.context.createMediaStreamSource(mediaStream);+ this.recorder = this.context.createScriptProcessor(BUFFER_SIZE, 1, 1);+ this.recorder.onaudioprocess = (event: AudioProcessingEvent) => {+ if (!this.isRecording || !this.worker) {+ return;+ }+ const input = event.inputBuffer.getChannelData(0);+ const pcm = new Int16Array(input.length);+ for (let i = 0; i < input.length; i++) {+ const sample = Math.max(-1, Math.min(1, input[i]));+ pcm[i] = sample < 0 ? sample * 0x8000 : sample * 0x7FFF;+ }+ this.worker.postMessage({type: "encode", buffer: pcm.buffer}, [pcm.buffer]);+ };+ this.audioInput.connect(this.recorder);+ this.recorder.connect(this.context.destination);}- public startRecordingNewWavFile() {- if (this.readyFlag) {- this.isRecording = true;- this.leftChannel.length = this.rightChannel.length = 0;- this.recordingLength = 0;+ public async startRecording() {+ if (this.disposed) {+ throw new Error("Recorder has been disposed");+ }+ if (this.isRecording) {+ return;}- }- public stopRecording() {- this.isRecording = false;+ this.chunks = [];+ this.readyPromise = new Promise<void>((resolve, reject) => {+ this.resolveReady = resolve;+ this.rejectReady = reject;+ });+ // Webpack 通过 import.meta.url 将录音编码器打包为按需加载的独立 Worker。+ // @ts-ignore TypeScript 的 CommonJS 类型检查不识别由 Webpack 转换的 import.meta.url。+ this.worker = new Worker(new URL("./RecordMediaWorker.ts", import.meta.url));+ this.worker.onmessage = (event: MessageEvent<EncoderMessage>) => {+ this.handleWorkerMessage(event.data);+ };+ this.worker.onerror = (event: ErrorEvent) => {+ this.handleWorkerError(new Error(event.message || "MP3 encoder failed"));+ };+ this.worker.postMessage({+ type: "init",+ sampleRate: this.context.sampleRate,+ bitRate: MP3_BIT_RATE,+ });+ await this.readyPromise;+ await this.context.resume();+ this.isRecording = true;}- public buildWavFileBlob() {- // we flat the left and right channels down- const leftBuffer = this.mergeBuffers(this.leftChannel);- const rightBuffer = this.mergeBuffers(this.rightChannel);-- // Interleave the left and right channels together:- let interleaved: Float32Array = new Float32Array(leftBuffer.length);-- for (let i = 0; i < leftBuffer.length; ++i) {- interleaved[i] = 0.5 * (leftBuffer[i] + rightBuffer[i]);- }-- // Downsample the audio data if necessary:- if (this.DEFAULT_SAMPLE_RATE > this.SAMPLE_RATE) {- interleaved = this.downSampleBuffer(interleaved, this.SAMPLE_RATE);+ public stopRecording() {+ if (this.stopPromise) {+ return this.stopPromise;}-- const totalByteCount = (44 + interleaved.length * 2);- const buffer = new ArrayBuffer(totalByteCount);- const view = new DataView(buffer);-- // Build the RIFF chunk descriptor:- this.writeUTFBytes(view, 0, "RIFF");- view.setUint32(4, totalByteCount, true);- this.writeUTFBytes(view, 8, "WAVE");-- // Build the FMT sub-chunk:- this.writeUTFBytes(view, 12, "fmt "); // subchunk1 ID is format- view.setUint32(16, 16, true); // The sub-chunk size is 16.- view.setUint16(20, 1, true); // The audio format is 1.- view.setUint16(22, 1, true); // Number of interleaved channels.- view.setUint32(24, this.SAMPLE_RATE, true); // Sample rate.- view.setUint32(28, this.SAMPLE_RATE * 2, true); // Byte rate.- view.setUint16(32, 2, true); // Block align- view.setUint16(34, 16, true); // Bits per sample.-- // Build the data sub-chunk:- const subChunk2ByteCount = interleaved.length * 2;- this.writeUTFBytes(view, 36, "data");- view.setUint32(40, subChunk2ByteCount, true);-- // Write the PCM samples to the view:- const lng = interleaved.length;- let index = 44;- const volume = 1;- for (let j = 0; j < lng; j++) {- view.setInt16(index, interleaved[j] * (0x7FFF * volume), true);- index += 2;+ if (!this.isRecording || !this.worker) {+ return Promise.reject(new Error("Recorder is not recording"));}- return new Blob([view], {type: "audio/wav"});+ this.isRecording = false;+ this.stopPromise = new Promise<Blob>((resolve, reject) => {+ this.resolveStop = resolve;+ this.rejectStop = reject;+ });+ this.worker.postMessage({type: "finish"});+ return this.stopPromise;}- private downSampleBuffer(buffer: Float32Array, rate: number) {- if (rate === this.DEFAULT_SAMPLE_RATE) {- return buffer;- }-- if (rate > this.DEFAULT_SAMPLE_RATE) {- // throw "downsampling rate show be smaller than original sample rate";- return buffer;+ public dispose() {+ if (this.disposed) {+ return;}-- const sampleRateRatio = this.DEFAULT_SAMPLE_RATE / rate;- const newLength = Math.round(buffer.length / sampleRateRatio);- const result = new Float32Array(newLength);- let offsetResult = 0;- let offsetBuffer = 0;-- while (offsetResult < result.length) {- const nextOffsetBuffer = Math.round((offsetResult + 1) * sampleRateRatio);- let accum = 0;- let count = 0;- for (let i = offsetBuffer; i < nextOffsetBuffer && i < buffer.length; i++) {- accum += buffer[i];- count++;- }- result[offsetResult] = accum / count;- offsetResult++;- offsetBuffer = nextOffsetBuffer;+ this.disposed = true;+ this.isRecording = false;+ this.recorder.onaudioprocess = null;+ this.audioInput.disconnect();+ this.recorder.disconnect();+ this.worker?.terminate();+ this.worker = undefined;+ this.mediaStream.getTracks().forEach((track) => track.stop());+ if (this.context.state !== "closed") {+ this.context.close();}- return result;}- private mergeBuffers(desiredChannelBuffer: Float32List[]) {- const result = new Float32Array(this.recordingLength);- let offset = 0;- const lng = desiredChannelBuffer.length;- for (let i = 0; i < lng; ++i) {- const buffer = desiredChannelBuffer[i];- result.set(buffer, offset);- offset += buffer.length;+ private handleWorkerMessage(message: EncoderMessage) {+ if (message.type === "ready") {+ this.resolveReady?.();+ } else if (message.type === "chunk") {+ this.chunks.push(message.buffer);+ } else if (message.type === "finished") {+ this.resolveStop?.(new Blob(this.chunks, {type: "audio/mpeg"}));+ } else if (message.type === "error") {+ this.handleWorkerError(new Error(message.message));}- return result;}- private writeUTFBytes(view: DataView, offset: number, value: string) {- const lng = value.length;- for (let i = 0; i < lng; i++) {- view.setUint8(offset + i, value.charCodeAt(i));- }+ private handleWorkerError(error: Error) {+ this.isRecording = false;+ this.rejectReady?.(error);+ this.rejectStop?.(error);+ this.onerror?.(error);}}diff --git a/app/src/protyle/util/RecordMediaWorker.ts b/app/src/protyle/util/RecordMediaWorker.tsnew file mode 100644index 0000000000..0c6aa3bf22--- /dev/null+++ b/app/src/protyle/util/RecordMediaWorker.ts@@ -0,0 +1,50 @@+/*! MP3 编码使用 @breezystack/lamejs,许可证为 LGPL-3.0:https://github.com/shijinyu/lamejs */+import {Mp3Encoder} from "@breezystack/lamejs";++type WorkerMessage =+ { type: "init", sampleRate: number, bitRate: number } |+ { type: "encode", buffer: ArrayBuffer } |+ { type: "finish" };++type WorkerScope = {+ onmessage: (event: MessageEvent<WorkerMessage>) => void;+ postMessage: (message: unknown, transfer?: Transferable[]) => void;+};++const workerScope = globalThis as unknown as WorkerScope;+let encoder: Mp3Encoder;++const postChunk = (chunk: Uint8Array) => {+ if (chunk.length === 0) {+ return;+ }+ const buffer = chunk.slice().buffer;+ workerScope.postMessage({type: "chunk", buffer}, [buffer]);+};++workerScope.onmessage = (event: MessageEvent<WorkerMessage>) => {+ try {+ const message = event.data;+ if (message.type === "init") {+ encoder = new Mp3Encoder(1, message.sampleRate, message.bitRate);+ workerScope.postMessage({type: "ready"});+ } else if (message.type === "encode") {+ if (!encoder) {+ throw new Error("MP3 encoder is not initialized");+ }+ postChunk(encoder.encodeBuffer(new Int16Array(message.buffer)));+ } else if (message.type === "finish") {+ if (!encoder) {+ throw new Error("MP3 encoder is not initialized");+ }+ postChunk(encoder.flush());+ encoder = undefined;+ workerScope.postMessage({type: "finished"});+ }+ } catch (error) {+ workerScope.postMessage({+ type: "error",+ message: error instanceof Error ? error.message : String(error),+ });+ }+};