forked from phildougherty/local_tts_reader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
244 lines (215 loc) · 6.48 KB
/
Copy pathbackground.js
File metadata and controls
244 lines (215 loc) · 6.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
let offscreenDocument = null;
let isRecording = false;
let currentPlayerState = 'stopped';
// Create or get the offscreen document
async function setupOffscreenDocument() {
// Check if we already have an offscreen document
const existingContexts = await chrome.runtime.getContexts({
contextTypes: ['OFFSCREEN_DOCUMENT']
});
if (existingContexts.length > 0) {
offscreenDocument = existingContexts[0];
return;
}
// Create an offscreen document
await chrome.offscreen.createDocument({
url: 'offscreen.html',
reasons: ['AUDIO_PLAYBACK'],
justification: 'Playing TTS audio in the background'
});
}
// Set up context menu items
function setupContextMenu() {
chrome.contextMenus.create({
id: "readAloud",
title: "Read Aloud",
contexts: ["selection", "page"]
});
}
// Handle context menu clicks
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "readAloud") {
let text = info.selectionText || "";
if (!text) {
// If no text is selected, get the page content
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: () => {
return document.body.innerText;
}
}).then(results => {
if (results && results[0] && results[0].result) {
processAndReadText(results[0].result, tab.id);
}
});
} else {
// Use the selected text
processAndReadText(text, tab.id);
}
}
});
// Process and read text with default settings
async function processAndReadText(text, tabId) {
try {
// Get default settings
const settings = await chrome.storage.local.get({
serverUrl: 'http://localhost:8000/v1/audio/speech',
voice: 'af_bella',
speed: 1.0,
recordAudio: false,
preprocessText: true
});
// Process text if enabled
if (settings.preprocessText && tabId) {
try {
// Inject the text processor script if needed
await chrome.scripting.executeScript({
target: { tabId: tabId },
files: ['textProcessor.js']
});
// Process the text
const result = await chrome.scripting.executeScript({
target: { tabId: tabId },
func: (textToProcess) => {
return window.TextProcessor.process(textToProcess);
},
args: [text]
});
if (result && result[0] && result[0].result) {
text = result[0].result;
}
} catch (error) {
console.error('Error processing text:', error);
// Fall back to using the original text
}
}
// Set state to loading
currentPlayerState = 'loading';
chrome.runtime.sendMessage({
type: 'playerStateUpdate',
state: 'loading'
});
// Start streaming audio
startStreamingAudio(text, settings);
} catch (error) {
console.error('Error in processAndReadText:', error);
chrome.runtime.sendMessage({
type: 'streamError',
error: error.message
});
}
}
// Handle messages from popup or offscreen document
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
switch (message.type) {
case 'setupOffscreen':
setupOffscreenDocument().then(() => sendResponse({ success: true }));
return true;
case 'startStreaming':
isRecording = message.record;
// Set state to loading before starting the audio stream
currentPlayerState = 'loading';
chrome.runtime.sendMessage({
type: 'playerStateUpdate',
state: 'loading'
});
startStreamingAudio(message.text, message.settings);
sendResponse({ success: true });
return true;
case 'controlAudio':
chrome.runtime.sendMessage({
type: message.action,
data: message.data
});
return true;
case 'stateUpdate':
currentPlayerState = message.state;
chrome.runtime.sendMessage({
type: 'playerStateUpdate',
state: message.state
});
return true;
case 'audioReady':
// Audio is ready but not yet playing
if (currentPlayerState === 'loading') {
currentPlayerState = 'ready';
chrome.runtime.sendMessage({
type: 'playerStateUpdate',
state: 'ready'
});
}
return true;
case 'getPlayerState':
sendResponse({ state: currentPlayerState });
return true;
case 'seek':
chrome.runtime.sendMessage({
type: 'seek',
time: message.time
}, (response) => {
sendResponse(response);
});
return true;
case 'getTimeInfo':
chrome.runtime.sendMessage({
type: 'getTimeInfo'
}, (response) => {
sendResponse(response);
});
return true;
case 'timeUpdate':
// Forward time updates to the popup
chrome.runtime.sendMessage(message);
return true;
}
});
// Start streaming audio from the TTS server
async function startStreamingAudio(text, settings) {
try {
await setupOffscreenDocument();
const response = await fetch(settings.serverUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'audio/mpeg, audio/wav, audio/*'
},
body: JSON.stringify({
model: 'tts-1',
voice: settings.voice,
input: text,
speed: parseFloat(settings.speed)
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Get the audio data as a blob
const audioBlob = await response.blob();
const mimeType = audioBlob.type || 'audio/mpeg';
// Convert blob to array buffer to send to offscreen document
const arrayBuffer = await audioBlob.arrayBuffer();
// Send the audio data to the offscreen document
chrome.runtime.sendMessage({
type: 'processAudioData',
audioData: Array.from(new Uint8Array(arrayBuffer)),
mimeType: mimeType,
isRecording: isRecording
});
} catch (error) {
console.error('Error streaming audio:', error);
chrome.runtime.sendMessage({
type: 'streamError',
error: error.message
});
// Update state to stopped on error
currentPlayerState = 'stopped';
chrome.runtime.sendMessage({
type: 'playerStateUpdate',
state: 'stopped'
});
}
}
// Initialize context menu when extension is installed or updated
chrome.runtime.onInstalled.addListener(() => {
setupContextMenu();
});