简体   繁体   English

Stream 音频直接从浏览器到服务器

[英]Stream audio directly from browser to server

I'd like to start uploading audio recorded from a mic as soon as the user hits Record , rather than wait until they're done.我想在用户点击Record后立即开始上传从麦克风录制的音频,而不是等到他们完成。 Is this possible with browser JavaScript?浏览器 JavaScript 可以做到这一点吗?

I tried this just to get started, but the request ends immediately instead of continuing as long as the recorder is recording.我尝试这样做只是为了开始,但只要录音机正在录音,请求就会立即结束,而不是继续。

Client (browser) code客户端(浏览器)代码

navigator.mediaDevices.getUserMedia({ audio: true }).then(
  (stream) => {
    const recorder = new MediaRecorder(stream)

    recorder.onstart = async () => {
      await fetch("/stream/upload", {
        method: "POST",
        headers: { "Content-Type": "multipart/form-data" },
        body: stream,
        allowHTTP1ForStreamingUpload: true,
      })

      console.log("Upload complete!")
    }
  },
  (err) => console.error("Error: " + err)
)

Server code服务器代码

const app = express()

app.post("/stream/upload", (req, res, next) => {
  res.status(200)

  req.on("data", (chunk) => {
    // only appears once
    console.log("Data received")
    res.write(chunk)
  })

  req.on("end", () => {
    // and then this appears immediately after
    console.log("Stream ended")
    res.send("Ended")
  })
})

onstart is only called when the recording start - you need to instead upload data as part of the dataavailable event - to make that event happen more frequently, use the timeslice parameter of the start method. onstart仅在录制开始时调用 - 您需要将数据作为dataavailable事件的一部分上传 - 要使该事件更频繁地发生,请使用start方法的timeslice参数。

That being said, depending on the underlying use case, you may be better served by using WebRTC to stream the audio content to the server.话虽如此,根据基础用例,使用 WebRTC 到 stream 将音频内容发送到服务器可能会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM