Skip to content

Commit

Permalink
fix: auto reconn stream danmu
Browse files Browse the repository at this point in the history
  • Loading branch information
zijiren233 committed Jan 17, 2025
1 parent b2d6acf commit 817fdf7
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 14 deletions.
2 changes: 1 addition & 1 deletion auto-imports.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@
// Generated by unplugin-auto-import
export {}
declare global {

const ElMessage: typeof import('element-plus/es')['ElMessage']
}
52 changes: 39 additions & 13 deletions src/plugins/danmu.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
type Danmu = string | {
text: string;
opacity?: number;
color?: string;
border?: boolean;
style?: {}
}
import { ElMessage } from "element-plus";

type Danmu =
| string
| {
text: string;
opacity?: number;
color?: string;
border?: boolean;
style?: {};
};

export function sendDanmu(msg: Danmu, art?: Artplayer) {
if (!art || !art.plugins.artplayerPluginDanmuku) return;
if (typeof msg === "string") {
art.plugins.artplayerPluginDanmuku.emit({
direct: true,
text: msg,
text: msg
});
} else {
art.plugins.artplayerPluginDanmuku.emit({
Expand All @@ -20,7 +24,7 @@ export function sendDanmu(msg: Danmu, art?: Artplayer) {
color: msg.color,
opacity: msg.opacity,
border: msg.border,
style: msg.style,
style: msg.style
});
}
}
Expand All @@ -29,16 +33,38 @@ export function sendDanmu(msg: Danmu, art?: Artplayer) {
export function artplayerStreamDanmu(streamURL: string) {
return (art: Artplayer) => {
let eventSource: EventSource | null = null;
art.once("video:canplay", () => {
let reconnectTimeout: number | null = null;

const connect = () => {
eventSource = new EventSource(streamURL);
eventSource.addEventListener("danmu", (event) => {
sendDanmu(event.data, art);
});
eventSource.onerror = (event) => {
console.error(event);
};
eventSource.addEventListener("error", (event) => {
console.error(`获取实时弹幕错误!${event}`);
if (eventSource?.readyState !== EventSource.CLOSED) {
return;
}

// 3秒后尝试重连
if (!reconnectTimeout) {
reconnectTimeout = window.setTimeout(() => {
ElMessage.warning("正在尝试重新连接弹幕服务器...");
connect();
reconnectTimeout = null;
}, 3000);
}
});
};

art.once("video:canplay", () => {
connect();
});

art.once("destroy", () => {
if (reconnectTimeout) {
clearTimeout(reconnectTimeout);
}
eventSource?.close();
});
};
Expand Down

0 comments on commit 817fdf7

Please sign in to comment.