diff --git a/app/danmu/controls.tsx b/app/danmu/controls.tsx index bd0de6c..5205cad 100644 --- a/app/danmu/controls.tsx +++ b/app/danmu/controls.tsx @@ -71,7 +71,7 @@ interface LyricItem { export default function Controls(): JSX.Element { const ref = useRef(null); const [history, setHistory] = useState([]); - const { songId, songName, songArtist } = useContext(DanmuContext); + const { songId, songName, songArtist, listener } = useContext(DanmuContext); const { start, resume, pause, setLyrics, offset, setOffset } = useLyricsRunner((line) => { @@ -82,6 +82,12 @@ export default function Controls(): JSX.Element { }, ...items, ]); + if (listener) { + // 测试用 + // listener('666'); + // 实际输出歌词 + listener(line.slice(0, 10)); + } console.log(line); }, 200); diff --git a/app/danmu/danmu.tsx b/app/danmu/danmu.tsx index c3c1f58..3603498 100644 --- a/app/danmu/danmu.tsx +++ b/app/danmu/danmu.tsx @@ -8,10 +8,27 @@ import { DanmuContext } from "./provider"; const MOMO_IM_URL = "wss://live-ws.immomo.com/ws/im"; +const useGenMessage = () => { + const [msgId, setMsgId] = useState(3); + return { + genMessage(text: string) { + const msg = { + msg_id: msgId, + client_time: Date.now(), + type: "Bili", + data: { text }, + }; + setMsgId(msgId + 1); + return msg; + }, + }; +}; + export default function Danmu({ token }: { token: Token }) { const [messageHistory, setMessageHistory] = useState[]>([]); const ref = useRef(null); - const { liveId, liveName } = useContext(DanmuContext); + const { liveId, dispatch } = useContext(DanmuContext); + const { genMessage } = useGenMessage(); const { sendMessage, lastMessage, readyState } = useWebSocket(MOMO_IM_URL, { heartbeat: { @@ -49,8 +66,17 @@ export default function Danmu({ token }: { token: Token }) { }; if (roomId) { sendMessage(JSON.stringify(data)); - console.log('重新连接...'); + console.log("重新连接..."); setMessageHistory([]); + dispatch({ + type: "listener", + payload: { + listener: (msg: string) => { + const data = genMessage(msg); + sendMessage(JSON.stringify(data)); + }, + }, + }); } } }, [readyState, roomId, momoId, momoToken]); diff --git a/app/danmu/provider.tsx b/app/danmu/provider.tsx index f9617de..a280e1c 100644 --- a/app/danmu/provider.tsx +++ b/app/danmu/provider.tsx @@ -7,6 +7,7 @@ export interface DanmuPayload { songId?: string; songName?: string; songArtist?: string; + listener?: (msg: string) => void; } export interface DanmuAction { @@ -30,6 +31,8 @@ const reducer = (state: DanmuPayload, action: DanmuAction): DanmuPayload => { }; case "lives": return { ...state, liveId: payload.liveId, liveName: payload.liveName }; + case "listener": + return { ...state, listener: payload.listener }; default: throw new Error("not support action"); }