最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Capturing audio with JavaScript and play it right away throws error at audio - Stack Overflow

programmeradmin3浏览0评论

I have a JavaScript file which should capture audio and then save it. When I started to work on saving it to the server, the first file was fine but all after were corrupted. So I decided to check in the browser what I'm sending. Then I figured out the same thing: the first audio clip is fine, but it kinda looks like that the second file is getting corrupted. I decided to check on another device to check if my laptop could cause the problem, but same issue. The error which im getting is super unclear for me: NotSupportedError: Failed to load because no supported source was found.. I used Chrome and Safari but both browsers and both laptops throw the same error.

Error from the console:

untitled.html:40 Blob {size: 81199, type: 'audio/webm'}
untitled.html:46 Playback failed: NotSupportedError: Failed to load because no supported source was found.
(anonymous) @ untitled.html:46
Promise.catch
playAudio @ untitled.html:46
mediaRecorder.ondataavailable @ untitled.html:27Understand this errorAI
untitled.html:40 Blob {size: 81536, type: 'audio/webm'}
untitled.html:46 Playback failed: NotSupportedError: Failed to load because no supported source was found.

HTML (to test, save it as a .html)

<html>
<head>
  <title>Example</title>
</head>

<script>

  let audioStream;
  let mediaRecorder;


  navigator.mediaDevices.getUserMedia({
    video: true,
    audio: true
  })
    .then(stream => {
      audioStream = new MediaStream(stream.getAudioTracks());
      mediaRecorder = new MediaRecorder(audioStream, {
        mimeType: "audio/webm"
      });



      mediaRecorder.ondataavailable = (event) => {

        if (event.data.size > 0) {
          playAudio(event.data);
        }
      };

      mediaRecorder.start(5000);
    })
    .catch(err => {
      console.error(err);
    });

  const playAudio = (audioChunk) => {
    const audioBlob = new Blob([audioChunk], { type: "audio/webm" }); // Ensure correct MIME type
    const audioUrl = URL.createObjectURL(audioBlob);
    console.log(audioBlob);

    const audioElement = document.createElement("audio");
    audioElement.src = audioUrl;
    audioElement.controls = true;
    document.body.appendChild(audioElement);
    audioElement.play().catch((e) => console.error("Playback failed:", e));
  };
</script>
</html>
发布评论

评论列表(0)

  1. 暂无评论