简体   繁体   中英

Read blob audio file on react app from blob storage served by azure function

I would get an audio file from azure storage and play it in my react app using react-h5-audio-player library.

Here's my azure function

import { AzureFunction, Context, HttpRequest } from "@azure/functions";

import {
  BlobServiceClient,
  StorageSharedKeyCredential,
} from "@azure/storage-blob";
import * as fs from "fs";

const storageAccountName = "interviewscoding";

const httpTrigger: AzureFunction = async function (
  context: Context,
  req: HttpRequest
): Promise<void> {
  const accountKey =
    "XXXXXXXXX";

  const meetingId = req.query.chatId;
  const containerName = req.query.containerName;
  try {
    const sharedKeyCredential = new StorageSharedKeyCredential(
      storageAccountName,
      accountKey
    );
    const blobServiceClient = new BlobServiceClient(
      `https://${storageAccountName}.blob.core.windows.net`,
      sharedKeyCredential
    );

    const containerClient = blobServiceClient.getContainerClient(containerName);
    const blobClient = containerClient.getBlobClient(`${meetingId}.wav`);
    const downloadBlockBlobResponse = await blobClient.download(0);

    context.res = {
      body: downloadBlockBlobResponse.readableStreamBody,
      headers: {
        "Content-Type": "audio/wav",
      },
    };
  } catch (error) {
    context.res = {
      body: error,
    };
  }
};

export default httpTrigger;

in my React app ( I have not detailed all the code ):

export function CandidatsStatus() {


  const [audioUrl, setAudioUrl] = useState<string | undefined>();


  const getAudio = async (item: CandidatsStatuses) => {
    const url = `${BASE_URL}${API_URLS.GET_MEETING_AUDIO}?chatId=${item.chatId}&containerName=oralaudios`;
    const response = await axios.get(url, {
      responseType: "blob",
    });
    const blob = new Blob([response.data], { type: "audio/wav" });
    const audio = URL.createObjectURL(blob);
    setAudioUrl(audio);
  };
  return (
    {audioUrl && <AudioPlayer src={audioUrl} autoPlay={false} />}

  )
}

When I play the audio nothing happens.

For information I downloaded the file from azure storage on azure portal, it plays well.

I think it's a mess when I send the stream on azure function?

I tried to log the blob variable ( on front end ):

Blob {size: 540525, type: 'audio/wav'}

I have found the solution right after writing the question so I would like to post it

I needed to convert stream to buffer:

function streamToBuffer(stream) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    stream.on("data", (data) => {
      chunks.push(Buffer.isBuffer(data) ? data : Buffer.from(data));
    });
    stream.on("end", () => {
      resolve(Buffer.concat(chunks));
    });
    stream.on("error", reject);
  });
}

Then use it in the function context response:

context.res = {
  body: await streamToBuffer(downloadBlockBlobResponse.readableStreamBody),
};

instead of

context.res = {
  body:downloadBlockBlobResponse.readableStreamBody,
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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