fix: fix ws

This commit is contained in:
熊潇 2025-06-23 10:38:01 +08:00
parent 203fa1f103
commit 767e436eb8
4 changed files with 24 additions and 19 deletions

View File

@ -27,7 +27,8 @@
"types": "types/index.d.ts",
"files": [
"dist",
"src"
"src",
"examples"
],
"publishConfig": {
"access": "public"
@ -83,7 +84,8 @@
"ws": "npm:@kevisual/ws"
},
"exports": {
"./src/*": "./src/*"
"./src/*": "./src/*",
"./examples/*": "./examples/*"
},
"packageManager": "pnpm@10.11.1"
}

View File

@ -1,4 +1,5 @@
// import WebSocket from 'ws';
import { EventEmitter } from 'eventemitter3';
import { WSServer, WSSOptions } from '../../provider/ws-server.ts';
export type VideoWSOptions = {
@ -9,6 +10,7 @@ export type VideoWSOptions = {
isFile?: boolean;
onConnect?: () => void;
wav_format?: string;
emitter?: EventEmitter;
} & {
wsOptions?: WSSOptions['wsOptions'];
};
@ -29,7 +31,7 @@ type OpenRequest = {
// '2pass' - 双通道模式, 'online' - 在线模式, 'offline' - 离线模式
mode: VideoWsMode;
// 音频格式:
wav_format?: string;
wav_format?: string; // 'wav' - PCM格式, 'mp3' - MP3格式等
// 音频采样率(单位: Hz):
audio_fs?: number;
// 热词列表:
@ -74,8 +76,6 @@ export class VideoWS extends WSServer {
request.wav_format = 'PCM';
request.audio_fs = file_sample_rate;
}
console.log('request', request);
this.ws.send(JSON.stringify(request));
}
async stop() {
@ -119,7 +119,11 @@ export class VideoWS extends WSServer {
const data = event.data;
try {
const result = JSON.parse(data.toString());
console.log('result', result);
if (result?.is_final !== undefined && result?.text) {
// console.log('result', result, typeof result);
this.emitter.emit('result', result);
}
console.log('onMessage-result', result);
} catch (error) {
console.log('error', error);
}

View File

@ -45,7 +45,7 @@ export class WSServer {
*/
async onOpen() {
this.connected = true;
this.onConnect();
this?.onConnect?.();
this.emitter.emit('open');
}
/**

View File

@ -1,6 +1,13 @@
const isBrowser = process?.env?.BROWSER === 'true' || typeof window !== 'undefined' && typeof window.document !== 'undefined';
import { EventEmitter } from 'events';
const isBrowser = process?.env?.BROWSER === 'true' || (typeof window !== 'undefined' && typeof window.document !== 'undefined');
const chantHttpToWs = (url: string) => {
if (url.startsWith('http://')) {
return url.replace('http://', 'ws://');
}
if (url.startsWith('https://')) {
return url.replace('https://', 'wss://');
}
return url;
};
type WebSocketOptions = {
/**
* , in node only
@ -11,6 +18,7 @@ type WebSocketOptions = {
};
export const initWs = async (url: string, options?: WebSocketOptions) => {
let ws: WebSocket;
url = chantHttpToWs(url);
if (isBrowser) {
ws = new WebSocket(url);
} else {
@ -30,12 +38,3 @@ interface EventEmitterOptions {
*/
captureRejections?: boolean | undefined;
}
/**
*
* @param opts
* @returns
*/
export const initEmitter = (opts?: EventEmitterOptions) => {
const emitter = new EventEmitter(opts);
return emitter;
};