I am receiving audio in a browser from WebRTC as a MediaStream. I need to convert it to an audio file, preferably an ogg. Ideally, the audio file will be uploaded to the server, but downloading it to the client as a file is the second best option.
I've learned how to upload audio in blobs, so if there is a way to save it to a Blob first, that should be good enough.
You cannot convert a stream directly on the fly into a File or Blob, as a MediaStream is an unlimited data source with no fixed start and end, even if you "just" stream a file from the other side of your connection. A Blob/File on the other hand has a fixed start and end. For conversion, you need to define a start and end somewhere.
Depending on your needs, there are countless options on how to actually set start and end boundaries, but it really depends on your needs which one to use (e.g. button press, onended event of the stream tracks, event from server, ...).
As @Kaiido pointed out, you can use MediaRecorder to convert parts of a MediaStream to Blob. Blobs can then be converted to File:
let recordedData = [];
const mediaRecorder = new MediaRecorder( yourIncomingStream, {mimeType: "audio/ogg"});
mediaRecorder.ondataavailable = (event) => {
/* add the data to the recordedDataArray */
recordedData.push(event.data)
}
/* this defines the start point - call when you want to start your audio to blob conversion */
function start() {
mediaRecorder.start();
}
/* this defines the end of your file, whenever called, a new file is
created from the recorded data */
function createFileFormCurrentRecordedData() {
const blob = new Blob(recordedData , {type: "audio/ogg"});
const file = new File( [ blob ], "yourfilename.ogg", { type: "audio/ogg"} );
/* then upload oder directly download your file / blob depending on your needs */
}
/* stop the recording */
function stop() {
mediaRecorder.stop();
}
/* if you don't need multiple recordings, you can listen to onstop */
mediaRecorder.onstop = createFileFormCurrentRecordedData;