Home > Blockchain >  Functions not streaming audio when deployed to production
Functions not streaming audio when deployed to production

Time:03-13

I have a firebase function that is designed to stream an audio as a response:

import fetch from "axios";
import * as functions from "firebase-functions";

export const testAudioStream = functions.https.onRequest(async (req, res) => {
    const urlToFile = "https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3";
    const range = req.headers.range;

    // get media response
    const mediaResponse = range
        ? await fetch(urlToFile, { headers: { range }, responseType: "stream" })
        : await fetch(urlToFile, { responseType: "stream" });

    mediaResponse.data.pipe(res);
});

When I run this in localhost (using postman), it works great:

enter image description here

But when I deploy it to production, the response is different than when I tested it in localhost:

enter image description here

I believe this is due to the response headers. In localhost, the response headers returned are:

enter image description here

But in production, the response headers are different:

enter image description here

So my questions are:

  1. Why are the results different depending on localhost and in production
  2. How do I make the production function return the audio correctly?

Edit: The intent here is to hide the file URL.

CodePudding user response:

Cloud Functions does not support streaming. The entire request and response are sent in one chunk. You may want to read the enter image description here

You could also return just the audio link and handle the link on the Front-end to properly play the returned audio.

CodePudding user response:

I solves this by just copying the headers to the response file:

// copy headers
const newHeaders = Object.entries(mediaResponse.headers);
for (const [key, value] of newHeaders)
    res.setHeader(key, value);

// copy status code
res.status(mediaResponse.status);
  • Related