简体   繁体   中英

RxJS run operation between each subscribe

I've implemented an angular pipe which speaks out the text passed.

I'm basically doing text to speech on a few sentences. The user needs to be able to see the sentence while the audio is playing... Not after the audio had finished (I have it currently like that).

Given an Observable of strings, how can I subscribe to each immediately, then play the audio until completion, before continuing with the rest of the strings?

transform(input: Observable<string>, ...args) {
  if (input) {
    return input.concatMap(text => {

      if (!text)
        return Observable.empty()

      let promise = Promise.resolve()
      .then(() =>
        this.service.textToSpeech(text)
      )
      .then((audio) =>
        new Promise<string>((resolve) => {
          player.play(audio)
          player.addEventListener("ended", () => {
            resolve(text)  // The user sees the text when the audio stops..
          })
        })
      )

      return Observable.fromPromise(promise)

    })
  }
}

I solved my problem by zipping with an offset like this (where f(a) is the audio for text a ):

a, null
b, f(a)
c, f(b)
null, f(c)

The code isn't pretty but it works... On the plus side, now the text-to-speech API requests aren't blocked by audio playback.

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