Home > Net >  Reproduce list of base64 encoding audios one by one
Reproduce list of base64 encoding audios one by one

Time:11-05

I have an array of Base64 encoded audios that I'm trying to reproduce one by one. The issue is that all elements are being reproduced at once. The following is my code.

You can download the audios.json

  async sayChunks() {
    const ttsResponses = await this.getTestJson();
    console.log("ttsResponses:", ttsResponses);
    for (const ttsResponse of ttsResponses) 
    {
      console.log("playing audio chunk");
      const encodedAudio = ttsResponse.base64Audio.replace(/['"] /g, '')
      await this.playAudio(encodedAudio);
      console.log("stopped playing audio chunk");
    }
  }

  async playAudio(encodedAudio: string) {
    return new Promise<void>((resolve) => {
      const audio = new Audio("data:audio/wav;base64,"   encodedAudio);
      audio.onended = () => resolve();
      audio.play();
    })
  }

CodePudding user response:

When you write an async function which return a Promise, you have to await the Promise when returning. Or you can directly return the Promise without making the function async.

Either:

  async playAudio(encodedAudio: string) {
    return await new Promise<void>((resolve) => {
      const audio = new Audio("data:audio/wav;base64,"   encodedAudio);
      audio.onended = () => resolve();
      audio.play();
    })
  }

Or simply:

  playAudio(encodedAudio: string) {
    return new Promise<void>((resolve) => {
      const audio = new Audio("data:audio/wav;base64,"   encodedAudio);
      audio.onended = () => resolve();
      audio.play();
    })
  }
  • Related