@rimori/react-client 0.4.8 → 0.4.9-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/ai/Assistant.js +1 -1
- package/dist/components/ai/Avatar.d.ts +2 -1
- package/dist/components/ai/Avatar.js +3 -3
- package/dist/components/audio/Playbutton.js +6 -2
- package/dist/hooks/UseChatHook.d.ts +3 -1
- package/dist/hooks/UseChatHook.js +3 -2
- package/dist/index.d.ts +0 -1
- package/dist/index.js +0 -1
- package/package.json +3 -3
- package/src/components/ai/Assistant.tsx +1 -1
- package/src/components/ai/Avatar.tsx +4 -2
- package/src/components/audio/Playbutton.tsx +7 -2
- package/src/hooks/UseChatHook.ts +5 -1
- package/src/index.ts +0 -1
- package/dist/components/ai/EmbeddedAssistent/TTS/MessageSender.d.ts +0 -21
- package/dist/components/ai/EmbeddedAssistent/TTS/MessageSender.js +0 -95
- package/dist/components/ai/EmbeddedAssistent/TTS/Player.d.ts +0 -29
- package/dist/components/ai/EmbeddedAssistent/TTS/Player.js +0 -205
- package/src/components/ai/EmbeddedAssistent/TTS/MessageSender.ts +0 -102
- package/src/components/ai/EmbeddedAssistent/TTS/Player.ts +0 -218
|
@@ -2,7 +2,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
|
2
2
|
import React, { useEffect, useMemo } from 'react';
|
|
3
3
|
import { CircleAudioAvatar } from './EmbeddedAssistent/CircleAudioAvatar';
|
|
4
4
|
import { AudioInputField } from './EmbeddedAssistent/AudioInputField';
|
|
5
|
-
import { MessageSender } from '
|
|
5
|
+
import { MessageSender } from '@rimori/client';
|
|
6
6
|
import Markdown from 'react-markdown';
|
|
7
7
|
import { useChat } from '../../hooks/UseChatHook';
|
|
8
8
|
import { useRimori } from '../../providers/PluginProvider';
|
|
@@ -9,6 +9,7 @@ interface Props {
|
|
|
9
9
|
children?: React.ReactNode;
|
|
10
10
|
autoStartConversation?: FirstMessages;
|
|
11
11
|
className?: string;
|
|
12
|
+
knowledgeId?: string;
|
|
12
13
|
}
|
|
13
|
-
export declare function Avatar({ avatarImageUrl, voiceId, agentTools, autoStartConversation, children, circleSize, className, cache, }: Props): import("react/jsx-runtime").JSX.Element;
|
|
14
|
+
export declare function Avatar({ avatarImageUrl, voiceId, agentTools, autoStartConversation, children, circleSize, className, cache, knowledgeId, }: Props): import("react/jsx-runtime").JSX.Element;
|
|
14
15
|
export {};
|
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
2
|
import { useEffect, useMemo, useState } from 'react';
|
|
3
3
|
import { VoiceRecorder } from './EmbeddedAssistent/VoiceRecorder';
|
|
4
|
-
import { MessageSender } from '
|
|
4
|
+
import { MessageSender } from '@rimori/client';
|
|
5
5
|
import { CircleAudioAvatar } from './EmbeddedAssistent/CircleAudioAvatar';
|
|
6
6
|
import { useChat } from '../../hooks/UseChatHook';
|
|
7
7
|
import { useRimori } from '../../providers/PluginProvider';
|
|
8
8
|
import { getFirstMessages } from './utils';
|
|
9
9
|
import { useTheme } from '../../hooks/ThemeSetter';
|
|
10
|
-
export function Avatar({ avatarImageUrl, voiceId, agentTools, autoStartConversation, children, circleSize = '300px', className, cache = false, }) {
|
|
10
|
+
export function Avatar({ avatarImageUrl, voiceId, agentTools, autoStartConversation, children, circleSize = '300px', className, cache = false, knowledgeId, }) {
|
|
11
11
|
const { ai, event, plugin } = useRimori();
|
|
12
12
|
const { isDark: isDarkThemeValue } = useTheme(plugin.theme);
|
|
13
13
|
const [agentReplying, setAgentReplying] = useState(false);
|
|
14
14
|
const [isProcessingMessage, setIsProcessingMessage] = useState(false);
|
|
15
15
|
const sender = useMemo(() => new MessageSender((...args) => ai.getVoice(...args), voiceId, cache), [voiceId, ai, cache]);
|
|
16
|
-
const { messages, append, isLoading, lastMessage, setMessages } = useChat(agentTools);
|
|
16
|
+
const { messages, append, isLoading, lastMessage, setMessages } = useChat(agentTools, { knowledgeId });
|
|
17
17
|
useEffect(() => {
|
|
18
18
|
console.log('messages', messages);
|
|
19
19
|
}, [messages]);
|
|
@@ -8,7 +8,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
8
8
|
});
|
|
9
9
|
};
|
|
10
10
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
11
|
-
import { useState, useEffect, useRef } from 'react';
|
|
11
|
+
import { useState, useEffect, useLayoutEffect, useRef } from 'react';
|
|
12
12
|
import { FaPlayCircle, FaStopCircle } from 'react-icons/fa';
|
|
13
13
|
import { useRimori } from '../../providers/PluginProvider';
|
|
14
14
|
import { EventBus } from '@rimori/client';
|
|
@@ -105,10 +105,14 @@ export const AudioPlayer = ({ text, voice, language, hide, playListenerEvent, in
|
|
|
105
105
|
setIsPlaying((prev) => !prev);
|
|
106
106
|
}
|
|
107
107
|
};
|
|
108
|
+
const togglePlaybackRef = useRef(togglePlayback);
|
|
109
|
+
useLayoutEffect(() => {
|
|
110
|
+
togglePlaybackRef.current = togglePlayback;
|
|
111
|
+
});
|
|
108
112
|
useEffect(() => {
|
|
109
113
|
if (!playListenerEvent)
|
|
110
114
|
return;
|
|
111
|
-
const handler = () =>
|
|
115
|
+
const handler = () => togglePlaybackRef.current();
|
|
112
116
|
const listener = EventBus.on(playListenerEvent, handler);
|
|
113
117
|
eventBusListenerRef.current = listener;
|
|
114
118
|
return () => {
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
2
|
import { Tool } from '@rimori/client';
|
|
3
3
|
import { Message } from '@rimori/client';
|
|
4
|
-
export declare function useChat(tools?: Tool[]
|
|
4
|
+
export declare function useChat(tools?: Tool[], options?: {
|
|
5
|
+
knowledgeId?: string | (() => string | undefined);
|
|
6
|
+
}): {
|
|
5
7
|
messages: Message[];
|
|
6
8
|
append: (appendMessages: Message[]) => void;
|
|
7
9
|
isLoading: boolean;
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
2
|
import { useRimori } from '../providers/PluginProvider';
|
|
3
|
-
export function useChat(tools) {
|
|
3
|
+
export function useChat(tools, options) {
|
|
4
4
|
const [messages, setMessages] = React.useState([]);
|
|
5
5
|
const [isLoading, setIsLoading] = React.useState(false);
|
|
6
6
|
const { ai } = useRimori();
|
|
7
7
|
const append = (appendMessages) => {
|
|
8
8
|
const allMessages = [...messages, ...appendMessages];
|
|
9
9
|
setMessages(allMessages);
|
|
10
|
+
const knowledgeId = typeof (options === null || options === void 0 ? void 0 : options.knowledgeId) === 'function' ? options.knowledgeId() : options === null || options === void 0 ? void 0 : options.knowledgeId;
|
|
10
11
|
ai.getSteamedText(allMessages, (id, message, finished, toolInvocations) => {
|
|
11
12
|
const lastMessage = messages[messages.length - 1];
|
|
12
13
|
setIsLoading(!finished);
|
|
@@ -17,7 +18,7 @@ export function useChat(tools) {
|
|
|
17
18
|
else {
|
|
18
19
|
setMessages([...allMessages, { id, role: 'assistant', content: message, toolCalls: toolInvocations }]);
|
|
19
20
|
}
|
|
20
|
-
}, tools);
|
|
21
|
+
}, tools, false, undefined, knowledgeId);
|
|
21
22
|
};
|
|
22
23
|
return {
|
|
23
24
|
messages,
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
export * from './hooks/UseChatHook';
|
|
2
2
|
export * from './providers/PluginProvider';
|
|
3
3
|
export * from './components/audio/Playbutton';
|
|
4
|
-
export * from './components/ai/EmbeddedAssistent/TTS/Player';
|
|
5
4
|
export * from './components/ai/Avatar';
|
|
6
5
|
export { FirstMessages } from './components/ai/utils';
|
|
7
6
|
export { useTranslation } from './hooks/I18nHooks';
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,6 @@
|
|
|
2
2
|
export * from './hooks/UseChatHook';
|
|
3
3
|
export * from './providers/PluginProvider';
|
|
4
4
|
export * from './components/audio/Playbutton';
|
|
5
|
-
export * from './components/ai/EmbeddedAssistent/TTS/Player';
|
|
6
5
|
export * from './components/ai/Avatar';
|
|
7
6
|
export { useTranslation } from './hooks/I18nHooks';
|
|
8
7
|
export { Avatar } from './components/ai/Avatar';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rimori/react-client",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.9-next.1",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"format": "prettier --write ."
|
|
24
24
|
},
|
|
25
25
|
"peerDependencies": {
|
|
26
|
-
"@rimori/client": "
|
|
26
|
+
"@rimori/client": "2.5.17-next.0",
|
|
27
27
|
"react": "^18.1.0",
|
|
28
28
|
"react-dom": "^18.1.0"
|
|
29
29
|
},
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
36
|
"@eslint/js": "^9.37.0",
|
|
37
|
-
"@rimori/client": "
|
|
37
|
+
"@rimori/client": "2.5.17-next.0",
|
|
38
38
|
"@types/react": "^18.3.21",
|
|
39
39
|
"eslint-config-prettier": "^10.1.8",
|
|
40
40
|
"eslint-plugin-prettier": "^5.5.4",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import React, { useEffect, useMemo } from 'react';
|
|
2
2
|
import { CircleAudioAvatar } from './EmbeddedAssistent/CircleAudioAvatar';
|
|
3
3
|
import { AudioInputField } from './EmbeddedAssistent/AudioInputField';
|
|
4
|
-
import { MessageSender } from '
|
|
4
|
+
import { MessageSender } from '@rimori/client';
|
|
5
5
|
import Markdown from 'react-markdown';
|
|
6
6
|
import { useChat } from '../../hooks/UseChatHook';
|
|
7
7
|
import { useRimori } from '../../providers/PluginProvider';
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { useEffect, useMemo, useState } from 'react';
|
|
2
2
|
import { VoiceRecorder } from './EmbeddedAssistent/VoiceRecorder';
|
|
3
|
-
import { MessageSender } from '
|
|
3
|
+
import { MessageSender } from '@rimori/client';
|
|
4
4
|
import { CircleAudioAvatar } from './EmbeddedAssistent/CircleAudioAvatar';
|
|
5
5
|
import { Tool } from '@rimori/client';
|
|
6
6
|
import { useChat } from '../../hooks/UseChatHook';
|
|
@@ -18,6 +18,7 @@ interface Props {
|
|
|
18
18
|
children?: React.ReactNode;
|
|
19
19
|
autoStartConversation?: FirstMessages;
|
|
20
20
|
className?: string;
|
|
21
|
+
knowledgeId?: string;
|
|
21
22
|
}
|
|
22
23
|
|
|
23
24
|
export function Avatar({
|
|
@@ -29,6 +30,7 @@ export function Avatar({
|
|
|
29
30
|
circleSize = '300px',
|
|
30
31
|
className,
|
|
31
32
|
cache = false,
|
|
33
|
+
knowledgeId,
|
|
32
34
|
}: Props) {
|
|
33
35
|
const { ai, event, plugin } = useRimori();
|
|
34
36
|
const { isDark: isDarkThemeValue } = useTheme(plugin.theme);
|
|
@@ -38,7 +40,7 @@ export function Avatar({
|
|
|
38
40
|
() => new MessageSender((...args) => ai.getVoice(...args), voiceId, cache),
|
|
39
41
|
[voiceId, ai, cache],
|
|
40
42
|
);
|
|
41
|
-
const { messages, append, isLoading, lastMessage, setMessages } = useChat(agentTools);
|
|
43
|
+
const { messages, append, isLoading, lastMessage, setMessages } = useChat(agentTools, { knowledgeId });
|
|
42
44
|
|
|
43
45
|
useEffect(() => {
|
|
44
46
|
console.log('messages', messages);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import React, { useState, useEffect, useRef } from 'react';
|
|
1
|
+
import React, { useState, useEffect, useLayoutEffect, useRef } from 'react';
|
|
2
2
|
import { FaPlayCircle, FaStopCircle } from 'react-icons/fa';
|
|
3
3
|
import { useRimori } from '../../providers/PluginProvider';
|
|
4
4
|
import { EventBus } from '@rimori/client';
|
|
@@ -129,9 +129,14 @@ export const AudioPlayer: React.FC<AudioPlayerProps> = ({
|
|
|
129
129
|
}
|
|
130
130
|
};
|
|
131
131
|
|
|
132
|
+
const togglePlaybackRef = useRef(togglePlayback);
|
|
133
|
+
useLayoutEffect(() => {
|
|
134
|
+
togglePlaybackRef.current = togglePlayback;
|
|
135
|
+
});
|
|
136
|
+
|
|
132
137
|
useEffect(() => {
|
|
133
138
|
if (!playListenerEvent) return;
|
|
134
|
-
const handler = () =>
|
|
139
|
+
const handler = () => togglePlaybackRef.current();
|
|
135
140
|
const listener = EventBus.on(playListenerEvent, handler);
|
|
136
141
|
eventBusListenerRef.current = listener;
|
|
137
142
|
|
package/src/hooks/UseChatHook.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { Tool } from '@rimori/client';
|
|
|
3
3
|
import { useRimori } from '../providers/PluginProvider';
|
|
4
4
|
import { Message, ToolInvocation } from '@rimori/client';
|
|
5
5
|
|
|
6
|
-
export function useChat(tools?: Tool[]) {
|
|
6
|
+
export function useChat(tools?: Tool[], options?: { knowledgeId?: string | (() => string | undefined) }) {
|
|
7
7
|
const [messages, setMessages] = React.useState<Message[]>([]);
|
|
8
8
|
const [isLoading, setIsLoading] = React.useState(false);
|
|
9
9
|
const { ai } = useRimori();
|
|
@@ -11,6 +11,7 @@ export function useChat(tools?: Tool[]) {
|
|
|
11
11
|
const append = (appendMessages: Message[]) => {
|
|
12
12
|
const allMessages = [...messages, ...appendMessages];
|
|
13
13
|
setMessages(allMessages);
|
|
14
|
+
const knowledgeId = typeof options?.knowledgeId === 'function' ? options.knowledgeId() : options?.knowledgeId;
|
|
14
15
|
ai.getSteamedText(
|
|
15
16
|
allMessages,
|
|
16
17
|
(id, message, finished: boolean, toolInvocations?: ToolInvocation[]) => {
|
|
@@ -25,6 +26,9 @@ export function useChat(tools?: Tool[]) {
|
|
|
25
26
|
}
|
|
26
27
|
},
|
|
27
28
|
tools,
|
|
29
|
+
false,
|
|
30
|
+
undefined,
|
|
31
|
+
knowledgeId,
|
|
28
32
|
);
|
|
29
33
|
};
|
|
30
34
|
|
package/src/index.ts
CHANGED
|
@@ -2,7 +2,6 @@
|
|
|
2
2
|
export * from './hooks/UseChatHook';
|
|
3
3
|
export * from './providers/PluginProvider';
|
|
4
4
|
export * from './components/audio/Playbutton';
|
|
5
|
-
export * from './components/ai/EmbeddedAssistent/TTS/Player';
|
|
6
5
|
export * from './components/ai/Avatar';
|
|
7
6
|
export { FirstMessages } from './components/ai/utils';
|
|
8
7
|
export { useTranslation } from './hooks/I18nHooks';
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
type VoiceBackend = (text: string, voice?: string, speed?: number, language?: string, cache?: boolean) => Promise<Blob>;
|
|
2
|
-
export declare class MessageSender {
|
|
3
|
-
private player;
|
|
4
|
-
private fetchedSentences;
|
|
5
|
-
private lastLoading;
|
|
6
|
-
private voice;
|
|
7
|
-
private voiceBackend;
|
|
8
|
-
private cache;
|
|
9
|
-
constructor(voiceBackend: VoiceBackend, voice: string, cache?: boolean);
|
|
10
|
-
private getCompletedSentences;
|
|
11
|
-
handleNewText(currentText: string | undefined, isLoading: boolean): Promise<void>;
|
|
12
|
-
private generateSpeech;
|
|
13
|
-
play(): void;
|
|
14
|
-
stop(): void;
|
|
15
|
-
cleanup(): void;
|
|
16
|
-
private reset;
|
|
17
|
-
setVolume(volume: number): void;
|
|
18
|
-
setOnLoudnessChange(callback: (value: number) => void): void;
|
|
19
|
-
setOnEndOfSpeech(callback: () => void): void;
|
|
20
|
-
}
|
|
21
|
-
export {};
|
|
@@ -1,95 +0,0 @@
|
|
|
1
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
-
});
|
|
9
|
-
};
|
|
10
|
-
import { ChunkedAudioPlayer } from './Player';
|
|
11
|
-
export class MessageSender {
|
|
12
|
-
constructor(voiceBackend, voice, cache = false) {
|
|
13
|
-
this.player = new ChunkedAudioPlayer();
|
|
14
|
-
this.fetchedSentences = new Set();
|
|
15
|
-
this.lastLoading = false;
|
|
16
|
-
if ((voice === null || voice === void 0 ? void 0 : voice.split('_').length) !== 2) {
|
|
17
|
-
throw new Error("Invalid voice id format '" + voice + "'. Voice id needs to look like <provider>_<voice_id>");
|
|
18
|
-
}
|
|
19
|
-
this.voiceBackend = voiceBackend;
|
|
20
|
-
this.voice = voice;
|
|
21
|
-
this.cache = cache;
|
|
22
|
-
}
|
|
23
|
-
getCompletedSentences(currentText, isLoading) {
|
|
24
|
-
// Split the text based on the following characters: .?!
|
|
25
|
-
// Only split on : when followed by a space
|
|
26
|
-
const pattern = /(.+?[.?!]|.+?:\s+|.+?\n+)/g;
|
|
27
|
-
const result = [];
|
|
28
|
-
let match;
|
|
29
|
-
while ((match = pattern.exec(currentText)) !== null) {
|
|
30
|
-
const sentence = match[0].trim();
|
|
31
|
-
if (sentence.length > 0) {
|
|
32
|
-
result.push(sentence);
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
if (!isLoading) {
|
|
36
|
-
const lastFullSentence = result[result.length - 1];
|
|
37
|
-
const leftoverIndex = currentText.lastIndexOf(lastFullSentence) + lastFullSentence.length;
|
|
38
|
-
if (leftoverIndex < currentText.length) {
|
|
39
|
-
result.push(currentText.slice(leftoverIndex).trim());
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
return result;
|
|
43
|
-
}
|
|
44
|
-
handleNewText(currentText, isLoading) {
|
|
45
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
46
|
-
if (!this.lastLoading && isLoading) {
|
|
47
|
-
this.reset();
|
|
48
|
-
}
|
|
49
|
-
this.lastLoading = isLoading;
|
|
50
|
-
if (!currentText) {
|
|
51
|
-
return;
|
|
52
|
-
}
|
|
53
|
-
const sentences = this.getCompletedSentences(currentText, isLoading);
|
|
54
|
-
for (let i = 0; i < sentences.length; i++) {
|
|
55
|
-
const sentence = sentences[i];
|
|
56
|
-
if (!this.fetchedSentences.has(sentence)) {
|
|
57
|
-
this.fetchedSentences.add(sentence);
|
|
58
|
-
const audioData = yield this.generateSpeech(sentence);
|
|
59
|
-
yield this.player.addChunk(audioData, i);
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
});
|
|
63
|
-
}
|
|
64
|
-
generateSpeech(sentence) {
|
|
65
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
66
|
-
const blob = yield this.voiceBackend(sentence, this.voice, 1.0, undefined, this.cache);
|
|
67
|
-
return yield blob.arrayBuffer();
|
|
68
|
-
});
|
|
69
|
-
}
|
|
70
|
-
play() {
|
|
71
|
-
this.player.playAgain();
|
|
72
|
-
}
|
|
73
|
-
stop() {
|
|
74
|
-
this.player.stopPlayback();
|
|
75
|
-
}
|
|
76
|
-
cleanup() {
|
|
77
|
-
this.player.cleanup();
|
|
78
|
-
}
|
|
79
|
-
reset() {
|
|
80
|
-
this.stop();
|
|
81
|
-
this.fetchedSentences.clear();
|
|
82
|
-
this.player.reset();
|
|
83
|
-
}
|
|
84
|
-
setVolume(volume) {
|
|
85
|
-
this.player.setVolume(volume);
|
|
86
|
-
}
|
|
87
|
-
setOnLoudnessChange(callback) {
|
|
88
|
-
this.player.setOnLoudnessChange((loudness) => {
|
|
89
|
-
callback(loudness);
|
|
90
|
-
});
|
|
91
|
-
}
|
|
92
|
-
setOnEndOfSpeech(callback) {
|
|
93
|
-
this.player.setOnEndOfSpeech(callback);
|
|
94
|
-
}
|
|
95
|
-
}
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
export declare class ChunkedAudioPlayer {
|
|
2
|
-
private audioContext;
|
|
3
|
-
private chunkQueue;
|
|
4
|
-
private isPlaying;
|
|
5
|
-
private analyser;
|
|
6
|
-
private dataArray;
|
|
7
|
-
private shouldMonitorLoudness;
|
|
8
|
-
private isMonitoring;
|
|
9
|
-
private handle;
|
|
10
|
-
private volume;
|
|
11
|
-
private loudnessCallback;
|
|
12
|
-
private currentIndex;
|
|
13
|
-
private startedPlaying;
|
|
14
|
-
private onEndOfSpeech;
|
|
15
|
-
private readonly backgroundNoiseLevel;
|
|
16
|
-
constructor();
|
|
17
|
-
private init;
|
|
18
|
-
setOnLoudnessChange(callback: (value: number) => void): void;
|
|
19
|
-
setVolume(volume: number): void;
|
|
20
|
-
addChunk(chunk: ArrayBuffer, position: number): Promise<void>;
|
|
21
|
-
private playChunks;
|
|
22
|
-
stopPlayback(): void;
|
|
23
|
-
cleanup(): void;
|
|
24
|
-
private playChunk;
|
|
25
|
-
playAgain(): Promise<void>;
|
|
26
|
-
private monitorLoudness;
|
|
27
|
-
reset(): void;
|
|
28
|
-
setOnEndOfSpeech(callback: () => void): void;
|
|
29
|
-
}
|
|
@@ -1,205 +0,0 @@
|
|
|
1
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
-
});
|
|
9
|
-
};
|
|
10
|
-
export class ChunkedAudioPlayer {
|
|
11
|
-
constructor() {
|
|
12
|
-
this.chunkQueue = [];
|
|
13
|
-
this.isPlaying = false;
|
|
14
|
-
this.shouldMonitorLoudness = true;
|
|
15
|
-
this.isMonitoring = false;
|
|
16
|
-
this.handle = 0;
|
|
17
|
-
this.volume = 1.0;
|
|
18
|
-
this.loudnessCallback = () => { };
|
|
19
|
-
this.currentIndex = 0;
|
|
20
|
-
this.startedPlaying = false;
|
|
21
|
-
this.onEndOfSpeech = () => { };
|
|
22
|
-
this.backgroundNoiseLevel = 30; // Background noise level that should be treated as baseline (0)
|
|
23
|
-
this.init();
|
|
24
|
-
}
|
|
25
|
-
init() {
|
|
26
|
-
this.audioContext = new AudioContext();
|
|
27
|
-
this.analyser = this.audioContext.createAnalyser();
|
|
28
|
-
this.analyser.fftSize = 256; // Set the FFT size (smaller values provide faster updates, larger ones give better resolution)
|
|
29
|
-
const bufferLength = this.analyser.frequencyBinCount;
|
|
30
|
-
this.dataArray = new Uint8Array(bufferLength); // Array to hold frequency data
|
|
31
|
-
}
|
|
32
|
-
setOnLoudnessChange(callback) {
|
|
33
|
-
this.loudnessCallback = callback;
|
|
34
|
-
}
|
|
35
|
-
setVolume(volume) {
|
|
36
|
-
this.volume = volume;
|
|
37
|
-
}
|
|
38
|
-
addChunk(chunk, position) {
|
|
39
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
40
|
-
console.log('Adding chunk', position, chunk);
|
|
41
|
-
this.chunkQueue[position] = chunk;
|
|
42
|
-
// console.log("received chunk", {
|
|
43
|
-
// chunkQueue: this.chunkQueue.length,
|
|
44
|
-
// isPlaying: this.isPlaying,
|
|
45
|
-
// })
|
|
46
|
-
if (position === 0 && !this.startedPlaying) {
|
|
47
|
-
this.startedPlaying = true;
|
|
48
|
-
this.playChunks();
|
|
49
|
-
}
|
|
50
|
-
});
|
|
51
|
-
}
|
|
52
|
-
playChunks() {
|
|
53
|
-
// console.log({ isPlaying: this.isPlaying });
|
|
54
|
-
if (this.isPlaying)
|
|
55
|
-
return;
|
|
56
|
-
if (!this.chunkQueue[this.currentIndex]) {
|
|
57
|
-
// wait until the correct chunk arrives
|
|
58
|
-
setTimeout(() => this.playChunks(), 10);
|
|
59
|
-
}
|
|
60
|
-
this.isPlaying = true;
|
|
61
|
-
this.playChunk(this.chunkQueue[this.currentIndex]).then(() => {
|
|
62
|
-
this.isPlaying = false;
|
|
63
|
-
this.currentIndex++;
|
|
64
|
-
if (this.chunkQueue[this.currentIndex]) {
|
|
65
|
-
this.shouldMonitorLoudness = true;
|
|
66
|
-
this.playChunks();
|
|
67
|
-
}
|
|
68
|
-
else {
|
|
69
|
-
// console.log('Playback finished', { currentIndex: this.currentIndex, chunkQueue: this.chunkQueue });
|
|
70
|
-
setTimeout(() => {
|
|
71
|
-
// console.log('Check again if really playback finished', { currentIndex: this.currentIndex, chunkQueue: this.chunkQueue });
|
|
72
|
-
if (this.chunkQueue.length > this.currentIndex) {
|
|
73
|
-
this.playChunks();
|
|
74
|
-
}
|
|
75
|
-
else {
|
|
76
|
-
this.startedPlaying = false;
|
|
77
|
-
this.shouldMonitorLoudness = false;
|
|
78
|
-
}
|
|
79
|
-
}, 1000);
|
|
80
|
-
}
|
|
81
|
-
});
|
|
82
|
-
}
|
|
83
|
-
stopPlayback() {
|
|
84
|
-
// console.log('Stopping playback');
|
|
85
|
-
// Implement logic to stop the current playback
|
|
86
|
-
this.isPlaying = false;
|
|
87
|
-
this.chunkQueue = [];
|
|
88
|
-
this.startedPlaying = false;
|
|
89
|
-
this.shouldMonitorLoudness = false;
|
|
90
|
-
cancelAnimationFrame(this.handle);
|
|
91
|
-
}
|
|
92
|
-
cleanup() {
|
|
93
|
-
// Stop playback first
|
|
94
|
-
this.stopPlayback();
|
|
95
|
-
// Close AudioContext to free resources
|
|
96
|
-
if (this.audioContext && this.audioContext.state !== 'closed') {
|
|
97
|
-
this.audioContext.close().catch((e) => {
|
|
98
|
-
console.warn('Error closing AudioContext:', e);
|
|
99
|
-
});
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
playChunk(chunk) {
|
|
103
|
-
// console.log({queue: this.chunkQueue})
|
|
104
|
-
if (!chunk) {
|
|
105
|
-
return Promise.resolve();
|
|
106
|
-
}
|
|
107
|
-
// console.log('Playing chunk', chunk);
|
|
108
|
-
return new Promise((resolve) => {
|
|
109
|
-
const source = this.audioContext.createBufferSource();
|
|
110
|
-
this.audioContext.decodeAudioData(chunk.slice(0)).then((audioBuffer) => {
|
|
111
|
-
source.buffer = audioBuffer;
|
|
112
|
-
// Create a GainNode for volume control
|
|
113
|
-
const gainNode = this.audioContext.createGain();
|
|
114
|
-
gainNode.gain.value = this.volume;
|
|
115
|
-
// Connect the source to the GainNode, then to the analyser node, then to the destination (speakers)
|
|
116
|
-
source.connect(gainNode);
|
|
117
|
-
gainNode.connect(this.analyser);
|
|
118
|
-
this.analyser.connect(this.audioContext.destination);
|
|
119
|
-
source.start(0);
|
|
120
|
-
// console.log('Playing chunk', this.currentIndex);
|
|
121
|
-
gainNode.gain.value = this.volume;
|
|
122
|
-
source.onended = () => {
|
|
123
|
-
// console.log('Chunk ended');
|
|
124
|
-
resolve();
|
|
125
|
-
};
|
|
126
|
-
// Start monitoring loudness only once
|
|
127
|
-
if (!this.isMonitoring) {
|
|
128
|
-
this.isMonitoring = true;
|
|
129
|
-
this.shouldMonitorLoudness = true;
|
|
130
|
-
this.monitorLoudness();
|
|
131
|
-
}
|
|
132
|
-
});
|
|
133
|
-
});
|
|
134
|
-
}
|
|
135
|
-
playAgain() {
|
|
136
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
137
|
-
console.log('Playing again');
|
|
138
|
-
if (this.chunkQueue.length > 0 && !this.isPlaying) {
|
|
139
|
-
this.playChunks();
|
|
140
|
-
}
|
|
141
|
-
});
|
|
142
|
-
}
|
|
143
|
-
monitorLoudness() {
|
|
144
|
-
// Stop monitoring when the flag is false
|
|
145
|
-
if (!this.shouldMonitorLoudness) {
|
|
146
|
-
// console.log('Loudness monitoring stopped.');
|
|
147
|
-
cancelAnimationFrame(this.handle);
|
|
148
|
-
this.loudnessCallback(0);
|
|
149
|
-
this.onEndOfSpeech();
|
|
150
|
-
return;
|
|
151
|
-
}
|
|
152
|
-
// Get the time domain data from the analyser (this is a snapshot of the waveform)
|
|
153
|
-
this.analyser.getByteTimeDomainData(this.dataArray);
|
|
154
|
-
// Calculate the RMS (root mean square) of the waveform values to get the perceived loudness
|
|
155
|
-
let sum = 0;
|
|
156
|
-
for (let i = 0; i < this.dataArray.length; i++) {
|
|
157
|
-
const value = this.dataArray[i] / 128.0 - 1.0; // Normalize between -1 and 1
|
|
158
|
-
sum += value * value;
|
|
159
|
-
}
|
|
160
|
-
const rms = Math.sqrt(sum / this.dataArray.length);
|
|
161
|
-
// Handle the case where RMS is 0 to avoid log10(0)
|
|
162
|
-
if (rms === 0) {
|
|
163
|
-
// console.log('Current loudness: Silent');
|
|
164
|
-
}
|
|
165
|
-
else {
|
|
166
|
-
let loudnessInDb = 20 * Math.log10(rms); // Convert to dB
|
|
167
|
-
// console.log('Current loudness:' + loudnessInDb);
|
|
168
|
-
const minDb = -57;
|
|
169
|
-
const maxDb = -15;
|
|
170
|
-
if (loudnessInDb < minDb) {
|
|
171
|
-
loudnessInDb = minDb;
|
|
172
|
-
}
|
|
173
|
-
if (loudnessInDb > maxDb) {
|
|
174
|
-
loudnessInDb = maxDb;
|
|
175
|
-
}
|
|
176
|
-
let loudnessScale = ((loudnessInDb - minDb) / (maxDb - minDb)) * 100;
|
|
177
|
-
// Adjust loudness: shift zero level up by background noise amount
|
|
178
|
-
// Values below background noise level are set to 0
|
|
179
|
-
// Values above are remapped to 0-100 scale
|
|
180
|
-
if (loudnessScale < this.backgroundNoiseLevel) {
|
|
181
|
-
loudnessScale = 0;
|
|
182
|
-
}
|
|
183
|
-
else {
|
|
184
|
-
// Remap from [backgroundNoiseLevel, 100] to [0, 100]
|
|
185
|
-
loudnessScale = ((loudnessScale - this.backgroundNoiseLevel) / (100 - this.backgroundNoiseLevel)) * 100;
|
|
186
|
-
}
|
|
187
|
-
this.loudnessCallback(Math.round(loudnessScale));
|
|
188
|
-
}
|
|
189
|
-
// Call this method again at regular intervals if you want continuous loudness monitoring
|
|
190
|
-
this.handle = requestAnimationFrame(() => this.monitorLoudness());
|
|
191
|
-
}
|
|
192
|
-
reset() {
|
|
193
|
-
// console.log('Resetting player');
|
|
194
|
-
this.stopPlayback();
|
|
195
|
-
this.currentIndex = 0;
|
|
196
|
-
this.shouldMonitorLoudness = true;
|
|
197
|
-
//reset to the beginning when the class gets initialized
|
|
198
|
-
this.isMonitoring = false;
|
|
199
|
-
this.isPlaying = false;
|
|
200
|
-
this.init();
|
|
201
|
-
}
|
|
202
|
-
setOnEndOfSpeech(callback) {
|
|
203
|
-
this.onEndOfSpeech = callback;
|
|
204
|
-
}
|
|
205
|
-
}
|
|
@@ -1,102 +0,0 @@
|
|
|
1
|
-
import { ChunkedAudioPlayer } from './Player';
|
|
2
|
-
|
|
3
|
-
type VoiceBackend = (text: string, voice?: string, speed?: number, language?: string, cache?: boolean) => Promise<Blob>;
|
|
4
|
-
|
|
5
|
-
export class MessageSender {
|
|
6
|
-
private player = new ChunkedAudioPlayer();
|
|
7
|
-
private fetchedSentences = new Set<string>();
|
|
8
|
-
private lastLoading = false;
|
|
9
|
-
private voice: string;
|
|
10
|
-
private voiceBackend: VoiceBackend;
|
|
11
|
-
private cache: boolean;
|
|
12
|
-
|
|
13
|
-
constructor(voiceBackend: VoiceBackend, voice: string, cache = false) {
|
|
14
|
-
if (voice?.split('_').length !== 2) {
|
|
15
|
-
throw new Error("Invalid voice id format '" + voice + "'. Voice id needs to look like <provider>_<voice_id>");
|
|
16
|
-
}
|
|
17
|
-
this.voiceBackend = voiceBackend;
|
|
18
|
-
this.voice = voice;
|
|
19
|
-
this.cache = cache;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
private getCompletedSentences(currentText: string, isLoading: boolean): string[] {
|
|
23
|
-
// Split the text based on the following characters: .?!
|
|
24
|
-
// Only split on : when followed by a space
|
|
25
|
-
const pattern = /(.+?[.?!]|.+?:\s+|.+?\n+)/g;
|
|
26
|
-
const result: string[] = [];
|
|
27
|
-
let match;
|
|
28
|
-
while ((match = pattern.exec(currentText)) !== null) {
|
|
29
|
-
const sentence = match[0].trim();
|
|
30
|
-
if (sentence.length > 0) {
|
|
31
|
-
result.push(sentence);
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
if (!isLoading) {
|
|
35
|
-
const lastFullSentence = result[result.length - 1];
|
|
36
|
-
const leftoverIndex = currentText.lastIndexOf(lastFullSentence) + lastFullSentence.length;
|
|
37
|
-
if (leftoverIndex < currentText.length) {
|
|
38
|
-
result.push(currentText.slice(leftoverIndex).trim());
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
return result;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
public async handleNewText(currentText: string | undefined, isLoading: boolean) {
|
|
45
|
-
if (!this.lastLoading && isLoading) {
|
|
46
|
-
this.reset();
|
|
47
|
-
}
|
|
48
|
-
this.lastLoading = isLoading;
|
|
49
|
-
|
|
50
|
-
if (!currentText) {
|
|
51
|
-
return;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
const sentences = this.getCompletedSentences(currentText, isLoading);
|
|
55
|
-
|
|
56
|
-
for (let i = 0; i < sentences.length; i++) {
|
|
57
|
-
const sentence = sentences[i];
|
|
58
|
-
if (!this.fetchedSentences.has(sentence)) {
|
|
59
|
-
this.fetchedSentences.add(sentence);
|
|
60
|
-
const audioData = await this.generateSpeech(sentence);
|
|
61
|
-
await this.player.addChunk(audioData, i);
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
private async generateSpeech(sentence: string): Promise<ArrayBuffer> {
|
|
67
|
-
const blob = await this.voiceBackend(sentence, this.voice, 1.0, undefined, this.cache);
|
|
68
|
-
return await blob.arrayBuffer();
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
public play() {
|
|
72
|
-
this.player.playAgain();
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
public stop() {
|
|
76
|
-
this.player.stopPlayback();
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
public cleanup() {
|
|
80
|
-
this.player.cleanup();
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
private reset() {
|
|
84
|
-
this.stop();
|
|
85
|
-
this.fetchedSentences.clear();
|
|
86
|
-
this.player.reset();
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
public setVolume(volume: number) {
|
|
90
|
-
this.player.setVolume(volume);
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
public setOnLoudnessChange(callback: (value: number) => void) {
|
|
94
|
-
this.player.setOnLoudnessChange((loudness) => {
|
|
95
|
-
callback(loudness);
|
|
96
|
-
});
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
public setOnEndOfSpeech(callback: () => void) {
|
|
100
|
-
this.player.setOnEndOfSpeech(callback);
|
|
101
|
-
}
|
|
102
|
-
}
|
|
@@ -1,218 +0,0 @@
|
|
|
1
|
-
export class ChunkedAudioPlayer {
|
|
2
|
-
private audioContext!: AudioContext;
|
|
3
|
-
private chunkQueue: ArrayBuffer[] = [];
|
|
4
|
-
private isPlaying = false;
|
|
5
|
-
private analyser!: AnalyserNode;
|
|
6
|
-
private dataArray!: Uint8Array<ArrayBuffer>;
|
|
7
|
-
private shouldMonitorLoudness = true;
|
|
8
|
-
private isMonitoring = false;
|
|
9
|
-
private handle = 0;
|
|
10
|
-
private volume = 1.0;
|
|
11
|
-
private loudnessCallback: (value: number) => void = () => {};
|
|
12
|
-
private currentIndex = 0;
|
|
13
|
-
private startedPlaying = false;
|
|
14
|
-
private onEndOfSpeech: () => void = () => {};
|
|
15
|
-
private readonly backgroundNoiseLevel = 30; // Background noise level that should be treated as baseline (0)
|
|
16
|
-
|
|
17
|
-
constructor() {
|
|
18
|
-
this.init();
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
private init(): void {
|
|
22
|
-
this.audioContext = new AudioContext();
|
|
23
|
-
this.analyser = this.audioContext.createAnalyser();
|
|
24
|
-
this.analyser.fftSize = 256; // Set the FFT size (smaller values provide faster updates, larger ones give better resolution)
|
|
25
|
-
const bufferLength = this.analyser.frequencyBinCount;
|
|
26
|
-
this.dataArray = new Uint8Array(bufferLength); // Array to hold frequency data
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
public setOnLoudnessChange(callback: (value: number) => void) {
|
|
30
|
-
this.loudnessCallback = callback;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
public setVolume(volume: number) {
|
|
34
|
-
this.volume = volume;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
public async addChunk(chunk: ArrayBuffer, position: number): Promise<void> {
|
|
38
|
-
console.log('Adding chunk', position, chunk);
|
|
39
|
-
this.chunkQueue[position] = chunk;
|
|
40
|
-
// console.log("received chunk", {
|
|
41
|
-
// chunkQueue: this.chunkQueue.length,
|
|
42
|
-
// isPlaying: this.isPlaying,
|
|
43
|
-
// })
|
|
44
|
-
|
|
45
|
-
if (position === 0 && !this.startedPlaying) {
|
|
46
|
-
this.startedPlaying = true;
|
|
47
|
-
this.playChunks();
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
private playChunks(): void {
|
|
52
|
-
// console.log({ isPlaying: this.isPlaying });
|
|
53
|
-
if (this.isPlaying) return;
|
|
54
|
-
if (!this.chunkQueue[this.currentIndex]) {
|
|
55
|
-
// wait until the correct chunk arrives
|
|
56
|
-
setTimeout(() => this.playChunks(), 10);
|
|
57
|
-
}
|
|
58
|
-
this.isPlaying = true;
|
|
59
|
-
|
|
60
|
-
this.playChunk(this.chunkQueue[this.currentIndex]).then(() => {
|
|
61
|
-
this.isPlaying = false;
|
|
62
|
-
this.currentIndex++;
|
|
63
|
-
if (this.chunkQueue[this.currentIndex]) {
|
|
64
|
-
this.shouldMonitorLoudness = true;
|
|
65
|
-
this.playChunks();
|
|
66
|
-
} else {
|
|
67
|
-
// console.log('Playback finished', { currentIndex: this.currentIndex, chunkQueue: this.chunkQueue });
|
|
68
|
-
setTimeout(() => {
|
|
69
|
-
// console.log('Check again if really playback finished', { currentIndex: this.currentIndex, chunkQueue: this.chunkQueue });
|
|
70
|
-
if (this.chunkQueue.length > this.currentIndex) {
|
|
71
|
-
this.playChunks();
|
|
72
|
-
} else {
|
|
73
|
-
this.startedPlaying = false;
|
|
74
|
-
this.shouldMonitorLoudness = false;
|
|
75
|
-
}
|
|
76
|
-
}, 1000);
|
|
77
|
-
}
|
|
78
|
-
});
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
public stopPlayback(): void {
|
|
82
|
-
// console.log('Stopping playback');
|
|
83
|
-
// Implement logic to stop the current playback
|
|
84
|
-
this.isPlaying = false;
|
|
85
|
-
this.chunkQueue = [];
|
|
86
|
-
this.startedPlaying = false;
|
|
87
|
-
this.shouldMonitorLoudness = false;
|
|
88
|
-
cancelAnimationFrame(this.handle);
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
public cleanup(): void {
|
|
92
|
-
// Stop playback first
|
|
93
|
-
this.stopPlayback();
|
|
94
|
-
// Close AudioContext to free resources
|
|
95
|
-
if (this.audioContext && this.audioContext.state !== 'closed') {
|
|
96
|
-
this.audioContext.close().catch((e) => {
|
|
97
|
-
console.warn('Error closing AudioContext:', e);
|
|
98
|
-
});
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
private playChunk(chunk: ArrayBuffer): Promise<void> {
|
|
103
|
-
// console.log({queue: this.chunkQueue})
|
|
104
|
-
if (!chunk) {
|
|
105
|
-
return Promise.resolve();
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
// console.log('Playing chunk', chunk);
|
|
109
|
-
return new Promise((resolve) => {
|
|
110
|
-
const source = this.audioContext.createBufferSource();
|
|
111
|
-
this.audioContext.decodeAudioData(chunk.slice(0)).then((audioBuffer) => {
|
|
112
|
-
source.buffer = audioBuffer;
|
|
113
|
-
|
|
114
|
-
// Create a GainNode for volume control
|
|
115
|
-
const gainNode = this.audioContext.createGain();
|
|
116
|
-
gainNode.gain.value = this.volume;
|
|
117
|
-
|
|
118
|
-
// Connect the source to the GainNode, then to the analyser node, then to the destination (speakers)
|
|
119
|
-
source.connect(gainNode);
|
|
120
|
-
gainNode.connect(this.analyser);
|
|
121
|
-
this.analyser.connect(this.audioContext.destination);
|
|
122
|
-
|
|
123
|
-
source.start(0);
|
|
124
|
-
// console.log('Playing chunk', this.currentIndex);
|
|
125
|
-
gainNode.gain.value = this.volume;
|
|
126
|
-
source.onended = () => {
|
|
127
|
-
// console.log('Chunk ended');
|
|
128
|
-
resolve();
|
|
129
|
-
};
|
|
130
|
-
|
|
131
|
-
// Start monitoring loudness only once
|
|
132
|
-
if (!this.isMonitoring) {
|
|
133
|
-
this.isMonitoring = true;
|
|
134
|
-
this.shouldMonitorLoudness = true;
|
|
135
|
-
this.monitorLoudness();
|
|
136
|
-
}
|
|
137
|
-
});
|
|
138
|
-
});
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
async playAgain(): Promise<void> {
|
|
142
|
-
console.log('Playing again');
|
|
143
|
-
if (this.chunkQueue.length > 0 && !this.isPlaying) {
|
|
144
|
-
this.playChunks();
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
private monitorLoudness(): void {
|
|
149
|
-
// Stop monitoring when the flag is false
|
|
150
|
-
if (!this.shouldMonitorLoudness) {
|
|
151
|
-
// console.log('Loudness monitoring stopped.');
|
|
152
|
-
cancelAnimationFrame(this.handle);
|
|
153
|
-
this.loudnessCallback(0);
|
|
154
|
-
this.onEndOfSpeech();
|
|
155
|
-
return;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
// Get the time domain data from the analyser (this is a snapshot of the waveform)
|
|
159
|
-
this.analyser.getByteTimeDomainData(this.dataArray);
|
|
160
|
-
|
|
161
|
-
// Calculate the RMS (root mean square) of the waveform values to get the perceived loudness
|
|
162
|
-
let sum = 0;
|
|
163
|
-
for (let i = 0; i < this.dataArray.length; i++) {
|
|
164
|
-
const value = this.dataArray[i] / 128.0 - 1.0; // Normalize between -1 and 1
|
|
165
|
-
sum += value * value;
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
const rms = Math.sqrt(sum / this.dataArray.length);
|
|
169
|
-
|
|
170
|
-
// Handle the case where RMS is 0 to avoid log10(0)
|
|
171
|
-
if (rms === 0) {
|
|
172
|
-
// console.log('Current loudness: Silent');
|
|
173
|
-
} else {
|
|
174
|
-
let loudnessInDb = 20 * Math.log10(rms); // Convert to dB
|
|
175
|
-
// console.log('Current loudness:' + loudnessInDb);
|
|
176
|
-
const minDb = -57;
|
|
177
|
-
const maxDb = -15;
|
|
178
|
-
|
|
179
|
-
if (loudnessInDb < minDb) {
|
|
180
|
-
loudnessInDb = minDb;
|
|
181
|
-
}
|
|
182
|
-
if (loudnessInDb > maxDb) {
|
|
183
|
-
loudnessInDb = maxDb;
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
let loudnessScale = ((loudnessInDb - minDb) / (maxDb - minDb)) * 100;
|
|
187
|
-
|
|
188
|
-
// Adjust loudness: shift zero level up by background noise amount
|
|
189
|
-
// Values below background noise level are set to 0
|
|
190
|
-
// Values above are remapped to 0-100 scale
|
|
191
|
-
if (loudnessScale < this.backgroundNoiseLevel) {
|
|
192
|
-
loudnessScale = 0;
|
|
193
|
-
} else {
|
|
194
|
-
// Remap from [backgroundNoiseLevel, 100] to [0, 100]
|
|
195
|
-
loudnessScale = ((loudnessScale - this.backgroundNoiseLevel) / (100 - this.backgroundNoiseLevel)) * 100;
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
this.loudnessCallback(Math.round(loudnessScale));
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
// Call this method again at regular intervals if you want continuous loudness monitoring
|
|
202
|
-
this.handle = requestAnimationFrame(() => this.monitorLoudness());
|
|
203
|
-
}
|
|
204
|
-
public reset() {
|
|
205
|
-
// console.log('Resetting player');
|
|
206
|
-
this.stopPlayback();
|
|
207
|
-
this.currentIndex = 0;
|
|
208
|
-
this.shouldMonitorLoudness = true;
|
|
209
|
-
//reset to the beginning when the class gets initialized
|
|
210
|
-
this.isMonitoring = false;
|
|
211
|
-
this.isPlaying = false;
|
|
212
|
-
this.init();
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
public setOnEndOfSpeech(callback: () => void) {
|
|
216
|
-
this.onEndOfSpeech = callback;
|
|
217
|
-
}
|
|
218
|
-
}
|