func.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // base64转arraybuffer
  2. export function base64ToArrayBuffer(base64String: string): ArrayBuffer {
  3. const binaryString = window.atob(base64String);
  4. const len = binaryString.length;
  5. const bytes = new Uint8Array(len);
  6. for (let i = 0; i < len; i++) {
  7. bytes[i] = binaryString.charCodeAt(i);
  8. }
  9. return bytes.buffer;
  10. }
  11. // blob转base64
  12. export function blobToBase64(blob: Blob): Promise<string> {
  13. return new Promise((resolve, reject) => {
  14. const reader = new FileReader();
  15. reader.onload = () => {
  16. if (typeof reader.result === 'string') {
  17. // 去掉 data:image/png;base64, 这样的前缀
  18. resolve(reader.result.split(',')[1]);
  19. } else {
  20. reject(new Error('Failed to read Blob as Base64'));
  21. }
  22. };
  23. reader.onerror = () => {
  24. reject(reader.error);
  25. };
  26. reader.readAsDataURL(blob);
  27. });
  28. }
  29. // tts文字前处理
  30. export function ttsTextPreprocess(text: string): string {
  31. const regex = /([\u4e00-\u9fa5a-zA-Z0-9\u3002\uFF0C\uFF1F\uFF01\uFF1A\u002E\u002C\u003F\u0021\u003A\u005B\u005D\u0028\u0029\\s\\]+)/g;
  32. // \u4e00-\u9fa5 对应中文字符
  33. // a-zA-Z 对应英文字符
  34. // 0-9 对应数字
  35. // \u3002 对应全角句号“。”
  36. // \u3002 对应全角句号“。”
  37. // \uFF0C 对应全角逗号“,”
  38. // \uFF1F 对应全角问号“?”
  39. // \uFF01 对应全角感叹号“!”
  40. // \uFF1A 对应全角冒号“:”
  41. // \u002E 对应半角句号“.”
  42. // \u002C 对应半角逗号“,”
  43. // \u003F 对应半角问号“?”
  44. // \u0021 对应半角感叹号“!”
  45. // \u003A 对应半角冒号“:”
  46. // \u005B 对应左方括号“[”
  47. // \u005D 对应右方括号“]”
  48. // \u0028 对应左圆括号“(”
  49. // \u0029 对应右圆括号“)”
  50. // \\ 对应 反斜杠“\”
  51. // \s 对应 空格
  52. const matches = text.match(regex);
  53. const processedText = matches ? matches.join(' ') : '';
  54. // const processedText = "\t当然!这是一个关于数字的笑话:\n\n为什么数字 7 总是觉得冷?\n"
  55. // 将换行符替换为句号
  56. const processedFilterText = processedText.replace(/\\n/g, ' ');
  57. // 将所有非中文字符或英文或则指定标签符号外的替换为空格
  58. return processedFilterText.trim();
  59. }