audio-capture-module.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. const { getAssemblyExports } = await globalThis.getDotnetRuntime(0);
  2. var nameSpace = (await getAssemblyExports("SimpleWebChat.BlazorWasm.dll")).SimpleWebChat.BlazorWasm.Modules;
  3. var DotNetInterop = nameSpace.AudioCaptureModule;
  4. var isRunning = false;
  5. var stream;
  6. var recorder;
  7. export async function init() {
  8. if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia)
  9. stream = await navigator.mediaDevices.getUserMedia({ audio: true });
  10. else throw "failure to getUserMedia";
  11. if (stream) {
  12. recorder = new MediaRecorder(stream, {
  13. audioBitsPerSecond: 64000,
  14. mimeType: 'audio/webm;codecs=OPUS'
  15. });
  16. recorder.ondataavailable = async (r) => {
  17. DotNetInterop.JsFeedChunk(new Uint8Array(await r.data.arrayBuffer()));
  18. };
  19. recorder.onstop = () => {
  20. if (isRunning) {
  21. recorder.start();
  22. setTimeout(() => {
  23. if (isRunning) recorder.stop();
  24. }, 1000);
  25. }
  26. };
  27. }
  28. return !!stream;
  29. }
  30. export async function start() {
  31. isRunning = true;
  32. if (recorder.state != 'recording') {
  33. recorder.start();
  34. setTimeout(() => {
  35. if (isRunning) recorder.stop();
  36. }, 1000);
  37. }
  38. }
  39. export async function stop() {
  40. isRunning = false;
  41. recorder.stop();
  42. }