Greasy Fork is available in English.

OpenAI TTS Text Reader

Read selected text with OpenAI's TTS API and adjustable volume and speed

اعتبارا من 20-11-2023. شاهد أحدث إصدار.

  1. // ==UserScript==
  2. // @name OpenAI TTS Text Reader
  3. // @namespace http://tampermonkey.net/
  4. // @version 2.6
  5. // @description Read selected text with OpenAI's TTS API and adjustable volume and speed
  6. // @include *
  7. // @grant GM_xmlhttpRequest
  8. // @connect api.openai.com
  9. // ==/UserScript==
  10. var YOUR_API_KEY = "sk-"; // 使用您的API密钥
  11. (function() {
  12. 'use strict';
  13. var currentSource = null;
  14. var isPlaying = false;
  15. var audioContext = new AudioContext();
  16. var gainNode = audioContext.createGain();
  17. gainNode.connect(audioContext.destination);
  18. var playbackRate = 1;
  19.  
  20. // 创建按钮
  21. var readButton = document.createElement("button");
  22. styleButton(readButton);
  23. document.body.appendChild(readButton);
  24.  
  25. // 创建并添加按钮文本
  26. var buttonText = document.createElement("span");
  27. buttonText.textContent = ">";
  28. styleButtonText(buttonText);
  29. readButton.appendChild(buttonText);
  30.  
  31. // 创建控制面板
  32. var controlPanel = document.createElement("div");
  33. styleControlPanel(controlPanel);
  34. document.body.appendChild(controlPanel);
  35.  
  36. // 创建并添加音量和速度滑块到控制面板
  37.  
  38. var volumeControl = createSlider("Volume", 0, 1, 0.5, 0.01, function(value) {
  39. gainNode.gain.value = value;
  40. });
  41. controlPanel.appendChild(volumeControl.wrapper);
  42. volumeControl.slider.value = 0.5; // 设置音量滑块的初始值为中间位置
  43. var speedControl = createSlider("Speed\u00A0\u00A0", 0.5, 1.5, 1, 0.05, function(value) { playbackRate = value; });
  44. controlPanel.appendChild(speedControl.wrapper);
  45. speedControl.slider.value = 1; // 设置音量滑块的初始值为中间位置
  46. // 按钮点击事件
  47. readButton.addEventListener('click', function() {
  48. var selectedText = window.getSelection().toString();
  49. console.log("Setting gainNode.gain.value to: ", gainNode.gain.value);
  50. if (isPlaying) {
  51. currentSource.stop(); // 停止当前播放的音频
  52. HideSpinner(buttonText);
  53. } else{
  54. if (selectedText) {
  55. textToSpeech(selectedText);
  56. } else {
  57. alert("请先选择一些文本。");
  58. }
  59. }
  60. });
  61.  
  62. // 创建和样式化控制面板和滑块
  63. function createSlider(labelText, min, max, value, step, onChange) {
  64. // 添加CSS样式到<head>
  65. var wrapper = document.createElement("div");
  66. var label = document.createElement("label");
  67. label.textContent = labelText;
  68. label.style.color = "white";
  69. label.style.textAlign = "left"; // 保持文字左对齐
  70. label.style.flex = "1"; // label会填充除了slider外的空间
  71.  
  72. var slider = document.createElement("input");
  73. slider.type = "range";
  74. slider.min = min;
  75. slider.max = max;
  76. slider.step = step;
  77.  
  78. // 设置wrapper使用Flexbox布局
  79. wrapper.style.display = 'flex';
  80. wrapper.style.alignItems = 'center'; // 垂直居中,但不影响文字
  81. wrapper.style.padding = '8px'; // 根据需要调整,为控件组添加内边距
  82.  
  83. var styleSheet = document.createElement("style");
  84. styleSheet.type = "text/css";
  85. styleSheet.innerText = `
  86. input[type='range'] {
  87. -webkit-appearance: none;
  88. appearance: none;
  89. width: 90%; // 可以根据需要调整滑块的宽度
  90. height: 8px; /* 调整轨道高度 */
  91. border-radius: 8px; /* 轨道边角圆滑 */
  92. background: rgba(255, 255, 255, 0.2); /* 轨道颜色 */
  93. outline: none;
  94. margin-left: 10px; // 为了与label对齐,可以根据需要调整
  95. }
  96.  
  97. input[type='range']::-webkit-slider-thumb {
  98. -webkit-appearance: none;
  99. appearance: none;
  100. width: 16px; /* 把手宽度 */
  101. height: 16px; /* 把手高度 */
  102. border-radius: 50%; /* 把手为圆形 */
  103. background: #4CAF50; /* 把手颜色 */
  104. cursor: pointer;
  105. box-shadow: 0 0 2px #888; /* 把手阴影 */
  106. }
  107.  
  108. input[type='range']:focus::-webkit-slider-thumb {
  109. background: #ccc; /* 把手聚焦时的颜色 */
  110. }
  111. `;
  112. document.head.appendChild(styleSheet);
  113.  
  114. // 创建滑块元素
  115. slider.oninput = function() {
  116. onChange(this.value);
  117. };
  118.  
  119. wrapper.appendChild(label);
  120. wrapper.appendChild(slider);
  121.  
  122. console.log("Setting volume to: ", value);
  123. return { wrapper: wrapper, slider: slider };
  124. }
  125. // 设置控制面板样式
  126. function styleControlPanel(panel) {
  127. panel.style.position = 'fixed';
  128. panel.style.bottom = '20px'; // 与按钮底部对齐
  129. panel.style.right = '80px';
  130. panel.style.width = '200px';
  131. panel.style.background = 'rgba(0, 0, 0, 0.7)';
  132. panel.style.borderRadius = '10px';
  133. panel.style.padding = '10px';
  134. panel.style.boxSizing = 'border-box';
  135. panel.style.visibility = 'hidden';
  136. panel.style.opacity = 0;
  137. panel.style.transition = 'opacity 0.5s, visibility 0.5s';
  138. panel.style.display = 'flex'; // 使用flex布局
  139. panel.style.flexDirection = 'column'; // 确保子元素垂直排列
  140. panel.style.zIndex = '10000';
  141. }
  142.  
  143. // 设置按钮样式
  144. function styleButton(button) {
  145. button.style.position = 'fixed';
  146. button.style.bottom = '20px';
  147. button.style.right = '20px';
  148. button.style.zIndex = '1000';
  149. button.style.width = '40px'; // 按钮宽度
  150. button.style.height = '40px'; // 按钮高度
  151. button.style.borderRadius = '50%'; // 圆形按钮
  152. button.style.backgroundColor = '#4CAF50';
  153. button.style.border = 'none'; // 确保没有边界
  154. button.style.outline = 'none'; // 确保没有轮廓
  155. button.style.cursor = 'pointer';
  156. button.style.transition = 'background-color 0.3s, opacity 0.4s ease';
  157. }
  158.  
  159. function styleButtonText(text) {
  160. text.style.transition = 'opacity 0.4s ease';
  161. text.style.opacity = '1';
  162. text.style.fontSize = "20px";
  163. text.style.textAlign = "center"; // 文本居中
  164. text.style.lineHeight = "40px"; // 设置行高以垂直居中文本
  165. }
  166.  
  167. function createVoiceSelect() {
  168. var selectWrapper = document.createElement("div");
  169. var select = document.createElement("select");
  170. var voices = ["alloy", "echo", "fable", "onyx", "nova", "shimmer"];
  171.  
  172. for (var i = 0; i < voices.length; i++) {
  173. var option = document.createElement("option");
  174. option.value = voices[i];
  175. option.textContent = voices[i].charAt(0).toUpperCase() + voices[i].slice(1);
  176. select.appendChild(option);
  177. }
  178.  
  179. selectWrapper.appendChild(select);
  180. styleSelect(selectWrapper, select);
  181. return { wrapper: selectWrapper, select: select };
  182. }
  183.  
  184. // 样式化下拉菜单
  185. function styleSelect(wrapper, select) {
  186. wrapper.style.padding = '5px';
  187. wrapper.style.marginBottom = '10px';
  188.  
  189. select.style.width = '100%';
  190. select.style.padding = '8px 10px';
  191. select.style.borderRadius = '8px';
  192. select.style.background = 'rgba(0, 0, 0, 0.7)'; // 调整背景为稍微透明的黑色
  193. select.style.border = '2px solid #4CAF50'; // 添加绿色边框
  194. select.style.color = 'white'; // 白色字体
  195. select.style.fontFamily = 'Arial, sans-serif';
  196. select.style.fontSize = '14px';
  197.  
  198. // 悬停效果
  199. select.onmouseover = function() {
  200. this.style.backgroundColor = 'rgba(50, 50, 50, 50.5)';
  201. };
  202.  
  203. // 鼠标离开效果
  204. select.onmouseout = function() {
  205. this.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
  206. };
  207.  
  208. // 聚焦效果
  209. select.onfocus = function() {
  210. this.style.outline = 'none';
  211. this.style.boxShadow = '0 0 5px rgba(81, 203, 238, 1)';
  212. };
  213. var styleSheet = document.createElement("style");
  214. styleSheet.type = "text/css";
  215. styleSheet.innerText = `
  216. select {
  217. /* 为 select 元素本身设置样式 */
  218. }
  219.  
  220. select option {
  221. background: rgba(0, 0, 0, 0.7); /* 选项背景设置为半透明黑色 */
  222. color: white; /* 文字颜色设置为白色 */
  223. }
  224.  
  225. select option:hover {
  226. background: rgba(0, 0, 0, 0.7); /* 悬浮时为半透明白色 */
  227. }
  228. `;
  229. document.head.appendChild(styleSheet);
  230. }
  231.  
  232. // 将音色选择下拉菜单添加到控制面板
  233. var voiceSelect = createVoiceSelect();
  234. controlPanel.appendChild(voiceSelect.wrapper);
  235. function textToSpeech(s) {
  236. var sModelId = "tts-1-hd";
  237. var sVoiceId = voiceSelect.select.value;
  238. var API_KEY = YOUR_API_KEY
  239.  
  240. ShowSpinner(buttonText); // 显示加载指示器
  241.  
  242. GM_xmlhttpRequest({
  243. method: "POST",
  244. url: "https://api.openai.com/v1/audio/speech",
  245. headers: {
  246. "Accept": "audio/mpeg",
  247. "Content-Type": "application/json",
  248. "Authorization": "Bearer " + API_KEY
  249. },
  250. data: JSON.stringify({
  251. model: sModelId,
  252. input: s,
  253. voice: sVoiceId,
  254. speed: playbackRate // 添加speed属性,使用全局变量playbackRate的值
  255. }),
  256. responseType: "arraybuffer",
  257.  
  258. onload: function(response) {
  259. if (response.status === 200) {
  260. HideSpinner(buttonText);
  261. audioContext.decodeAudioData(response.response, function(buffer) {
  262. var source = audioContext.createBufferSource();
  263. source.buffer = buffer;
  264. source.connect(gainNode);
  265. source.start(0);
  266. currentSource = source; // 保存新的音频源
  267. isPlaying = true;
  268. StopSpinner(buttonText); // 更新按钮文本
  269.  
  270. // 监听音频结束事件
  271. source.onended = function() {
  272. isPlaying = false;
  273. //currentSource = null;
  274. HideSpinner(buttonText);
  275. } // 更新按钮文本
  276. }, function(e) {
  277. console.error("Error decoding audio data: ", e);
  278. });
  279. } else {
  280. HideSpinner(buttonText);
  281. console.error("Error loading TTS: ", response.status);
  282. }
  283. },
  284. onerror: function(error) {
  285. HideSpinner(buttonText);
  286. console.error("GM_xmlhttpRequest error: ", error);
  287. }
  288. });
  289. }
  290.  
  291.  
  292.  
  293. // 设置延迟显示和隐藏控制面板的时间(以毫秒为单位)
  294. var panelDisplayDelay = 700; // 700毫秒
  295. var panelHideDelay = 500; // 隐藏延迟时间
  296. var showPanelTimeout, hidePanelTimeout;
  297.  
  298. // 鼠标悬停在按钮上时延迟显示控制面板
  299. readButton.addEventListener('mouseenter', function() {
  300. readButton.style.backgroundColor = '#45a049';
  301. clearTimeout(hidePanelTimeout); // 取消之前的隐藏计时器(如果有)
  302. showPanelTimeout = setTimeout(function() {
  303. controlPanel.style.visibility = 'visible';
  304. controlPanel.style.opacity = 1;
  305. }, panelDisplayDelay);
  306. });
  307.  
  308. // 鼠标离开按钮时延迟隐藏控制面板
  309. readButton.addEventListener('mouseleave', function() {
  310. readButton.style.backgroundColor = '#4CAF50';
  311. clearTimeout(showPanelTimeout); // 取消之前的显示计时器(如果有)
  312. hidePanelTimeout = setTimeout(function() {
  313. controlPanel.style.visibility = 'hidden';
  314. controlPanel.style.opacity = 0;
  315. }, panelHideDelay);
  316. });
  317.  
  318. // 鼠标在控制面板上时保持显示状态
  319. controlPanel.addEventListener('mouseenter', function() {
  320. clearTimeout(hidePanelTimeout); // 取消隐藏计时器
  321. controlPanel.style.visibility = 'visible';
  322. controlPanel.style.opacity = 1;
  323. });
  324.  
  325. // 鼠标离开控制面板时延迟隐藏
  326. controlPanel.addEventListener('mouseleave', function() {
  327. hidePanelTimeout = setTimeout(function() {
  328. controlPanel.style.visibility = 'hidden';
  329. controlPanel.style.opacity = 0;
  330. }, panelHideDelay);
  331. });
  332. speedControl.slider.addEventListener('input', function() {
  333. playbackRate = this.value;
  334. });
  335. function ShowSpinner(text) {
  336. text.style.opacity = '0';
  337. setTimeout(function() {
  338. text.textContent = "...";
  339. text.style.opacity = '1';
  340. }, 400); // 等待与 transition 时间一致
  341. readButton.disabled = true; // 禁用按钮以防止重复点击
  342. }
  343.  
  344. function HideSpinner(text) {
  345. text.style.opacity = '0';
  346. setTimeout(function() {
  347. text.textContent = ">";
  348. text.style.opacity = '1';
  349. }, 400); // 等待与 transition 时间一致
  350. readButton.disabled = false; //
  351. }
  352. function StopSpinner(text) {
  353. text.style.opacity = '0';
  354. setTimeout(function() {
  355. text.textContent = "│▌";
  356. text.style.opacity = '1';
  357. }, 400); // 等待与 transition 时间一致
  358. //readButton.disabled = false; //
  359. }
  360. })();