An Audio Player hook to your React App
This was my seventh week of contributing to ChatCraft, and thus far, I’ve efficiently shipped varied enhancements to the prevailing system. Every week, I’ve tried so as to add new options to the app and since we’re delivery code shortly, many time its not attainable to deal with every side of the problem completely and comply with ups should be filed.
Just a few weeks in the past, I used OpenAI’s textual content to speech API enabling ChatCraft to announce LLM responses as they have been generated.
I attempted to parse the responses into sentences, go these chunks to tts api for audio technology, and in the end play the generated audio clips in sequence.
I’ve already written about the whole course of in this publish. In this publish, I’ll talk about one of many shortcomings of that characteristic, and the way I up to date my AudioPlayer hook to handle the orchestrate the ordered playback of audio chunks all through the applying.
Table of Contents
1. The Problem ⁉️
2. Implementing a world audio Queue
2.1. Defining an Audio Player Context
2.2. Wrapping the audio queue in a Context Provider
2.3. Providing the context
2.4. Defining useAudioPlayerHook
2.5. Using the Hook 🪝
3. The Pull Request 📝
4. Reviewing a PR that provides Custom Provider Classes
5. What’s Ahead 🔜
The Problem ⁉️
If you went via my publish, you might need observed that to be able to protect the order of audio chunks, I used to be sustaining a basic queue knowledge construction inside my hook.
Here’s the code for fast recap:
import { useState, useEffect } from "react";
const useAudioPlayer = () => {
// We are managing guarantees of audio urls as a substitute of instantly storing strings
// as a result of there isn't a assure when openai tts api finishes processing and resolves a particular url
// For extra data, examine this remark:
// https://github.com/tarasglek/chatcraft.org/pull/357#discussion_r1473470003
const [queue, setQueue] = useState<Promise<string>[]>([]);
const [isPlaying, setIsPlaying] = useState<boolean>(false);
useEffect(() => {
if (!isPlaying && queue.size > 0) {
playAudio(queue[0]);
}
}, [queue, isPlaying]);
const playAudio = async (audioClipUri: Promise<string>) => {
setIsPlaying(true);
const audioUrl: string = await audioClipUri;
const audio = new Audio(audioUrl);
audio.onended = () => {
URL.revokeObjectURL(audioUrl); // To keep away from reminiscence leaks
setQueue((outdatedQueue) => outdatedQueue.slice(1));
setIsPlaying(false);
};
audio.play();
};
const addToAudioQueue = (audioClipUri: Promise<string>) => {
setQueue((outdatedQueue) => [...oldQueue, audioClipUri]);
};
return { addToAudioQueue };
};
export default useAudioPlayer;
Now this works like a Charm, when you’re solely utilizing this hook at only one place within the app. But think about what would occur if I used to be to make use of this hook from another a part of the app as effectively.
const { addToAudioQueue } = useAudioPlayer();
const audioClipUri = textual contentToSpeech(ttsWordsBuffer);
addToAudioQueue(audioClipUri);
- Would it nonetheless preserve the order?
- Leave the order apart, is there a assure there may be solely a single audio clip taking part in at some extent of time.
The reply, as you might need guessed is a NO ❌
Reason being, each time we name the useAudioPlayer hook, it returns a contemporary occasion of an audio queue. Let’s say you utilize it at 3 completely different locations in your app, you now have 3 audio gamers lively on the similar time.
And for those who push audio clips to one among them whereas one other is already taking part in one thing, you get into an analogous scenario as for those who there are 3 audio system in a room, and each is taking part in a distinct track.
This did not stop me from merging the prevailing code as I used to be solely initializing an audio queue at one place all through the applying.
But with this, there was no method to entry and function with the audio queue from different elements of the applying, like stopping the audio playback when a brand new query is requested.
The particulars are documented on this comply with up.

Stop taking part in audio when tts is turned off
#391
Implementing a world audio Queue
To repair this difficulty, I needed to make it possible for there was all the time solely one occasion of the audio queue all through the applying, whereas the core logic and interface would stay the identical.
This needed to be carried out within the following steps.
Defining an Audio Player Context
The first step was to outline a React Context, that may expose the related capabilities to function with the audio queue.
kind AudioPlayerContextKind = {
addToAudioQueue: (audioClipUri: Promise<string>) => void;
clearAudioQueue: () => void;
};
const AudioPlayerContext = createContext<AudioPlayerContextKind>({
addToAudioQueue: () => {},
clearAudioQueue: () => {},
});
Notice that I’m additionally exposing a brand new technique known as clearAudioQueue now. We’ll have a look at the implementation quickly.
Wrapping the audio queue in a Context Provider
For any of the elements in a React Application to learn from a context, it first must be supplied to one among its ancestors.
This is finished with the assistance of a React Context Provider. I wrapped the prevailing audio participant logic right into a perform that returns an AudioPlayerContext Provider exposing the capabilities that might be used to function on the single Audio Queue within the app.
import { useState, useEffect, createContext, useContext, ReactNode, FC } from "react";
kind AudioClip = {
audioUrl: string;
audioElement: HTMLAudioComponent;
};
export const AudioPlayerProvider: FC<{ youngsters: ReactNode }> = ({ youngsters }) => {
// We are managing guarantees of audio urls as a substitute of instantly storing strings
// as a result of there isn't a assure when openai tts api finishes processing and resolves a particular url
// For extra data, examine this remark:
// https://github.com/tarasglek/chatcraft.org/pull/357#discussion_r1473470003
const [queue, setQueue] = useState<Promise<string>[]>([]);
const [isPlaying, setIsPlaying] = useState<boolean>(false);
const [currentAudioClip, setCurrentAudioClip] = useState<AudioClip | null>();
useEffect(() => {
if (!isPlaying && queue.size > 0) {
playAudio(queue[0]);
}
}, [queue, isPlaying]);
const playAudio = async (audioClipUri: Promise<string>) => {
setIsPlaying(true);
const audioUrl: string = await audioClipUri;
const audio = new Audio(audioUrl);
audio.preload = "auto";
audio.onended = () => {
URL.revokeObjectURL(audioUrl);
setQueue((outdatedQueue) => outdatedQueue.slice(1));
setIsPlaying(false);
setCurrentAudioClip(null);
};
audio.play();
setCurrentAudioClip({
audioElement: audio,
audioUrl: audioUrl,
});
};
const addToAudioQueue = (audioClipUri: Promise<string>) => {
setQueue((outdatedQueue) => [...oldQueue, audioClipUri]);
};
const clearAudioQueue = () => {
if (presentAudioClip) {
// Stop at present taking part in audio
presentAudioClip.audioElement.pause();
URL.revokeObjectURL(presentAudioClip.audioUrl);
setCurrentAudioClip(null);
setIsPlaying(false);
}
// Flush all of the remaining audio clips
setQueue([]);
};
const worth = { addToAudioQueue, clearAudioQueue };
return <AudioPlayerContext.Provider worth={worth}>{youngsters}</AudioPlayerContext.Provider>;
};
You’ll discover the implementation of the clearAudioQueue perform, which is supposed to be known as from any software part to pause the present audio clip, and flush the remaining clips within the queue.
I’m additionally managing a brand new state now
kind AudioClip = {
audioUrl: string;
audioElement: HTMLAudioComponent;
};
const [currentAudioClip, setCurrentAudioClip] = useState<AudioClip | null>();
This permits me to pause the present taking part in audio as quickly because the clearAudioQueue perform is named.
Providing the context
The subsequent step is to offer the AudioPlayerContext on the root of the applying.
In primary.tsx
import { AudioPlayerProvider } from "./hooks/use-audio-player";
ReactDOM.createRoot(doc.querySelector("primary") as HTMLElement).render(
<React.StrictMode>
<ChakraProvider theme={theme}>
<AudioPlayerProvider>
<SettingsProvider>
<ValueProvider>
<FashionsProvider>
<PersonProvider>
<ColorModeScript initialColorMode={theme.config.initialColorMode} />
<RouterProvider router={router} />
</PersonProvider>
</FashionsProvider>
</ValueProvider>
</SettingsProvider>
</AudioPlayerProvider>
</ChakraProvider>
</React.StrictMode>
);
Defining useAudioPlayerHook
After defining the context and supplier, we will lastly write the hook to make use of the AudioPlayerContext supplied by the closest context supplier.
const useAudioPlayer = () => useContext(AudioPlayerContext);
export default useAudioPlayer;
Using the Hook 🪝
And the ultimate step was to truly use the worldwide Audio Player context at locations I want to.
Currently, I’m utilizing it for two situations:
1. The audio for earlier message will immediately cease taking part in as quickly because the consumer asks a brand new query.
import useAudioPlayer from "../../hooks/use-audio-player";
...
...
const { clearAudioQueue } = useAudioPlayer();
...
...
// NOTE: we strip out the ChatCraft App messages earlier than sending to OpenAI.
const messages = chat.messages({ embraceAppMessages: false });
// Clear any earlier audio clips
clearAudioQueue();
const response = await callChatApi(messages, {
capabilities,
performToName,
});
2. Any audio clips being performed by way of useAudioPlayer will immediately cease as quickly because the consumer disables the TTS setting.
import useAudioPlayer from "../../hooks/use-audio-player";
...
...
const { clearAudioQueue } = useAudioPlayer();
...
...
{isTtsSupported && (
<Tooltip
label={settings.announceMessages ? "Text-to-Speech Enabled" : "Text-to-Speech Disabled"}
>
<IconButton
kind="button"
measurement="lg"
variant="stable"
aria-label={
settings.announceMessages ? "Text-to-Speech Enabled" : "Text-to-Speech Disabled"
}
icon={
settings.announceMessages ? <MdVolumeUp measurement={25} /> : <MdVolumeOff measurement={25} />
}
onClick={() => {
if (settings.announceMessages) {
// Flush any remaining audio clips being introduced
clearAudioQueue();
}
setSettings({ ...settings, announceMessages: !settings.announceMessages });
}}
/>
</Tooltip>
)}
And that’s all it takes to create and use a customized audio participant hook in a React Application. I’m fairly positive there are audio participant hooks already revealed on npm, however I doubt any of them will match my wants as I want to take care of a queue.
Let me know within the feedback if a greater method.
The Pull Request 📝
My PR for this enchancment is already up awaiting opinions earlier than it will get landed.
You can have a look at the whole supply code and an in depth clarification right here.

Make AudioPlayer queue world
#484
In #357, I used to be capable of stream audio responses because the LLM response was generated and likewise optimize the playback.
But there have been some issues with it, and comply with ups have been filed.
This is relating to a kind of comply with ups – #391.
The drawback was that when an audio clip was added to the audio queue, there was no method to cease it from different elements of the applying since each invocation to useAudioPlayer hook resulted in a contemporary audio queue. This was fairly annoying and made the TTS characteristic unusable as customers needed to look ahead to the earlier message announcement to complete earlier than it began taking part in for the subsequent one.
To repair this difficulty, I’ve made the Audio Player queue world, by creating and offering an AudioPlayerContext on the root of the applying.
This allowed me to reveal one other perform from the hook known as clearAudioQueue which might now be known as from any software part to pause the present audio clip, and flush the remaining clips within the queue.
Currently, I’m utilizing it for two situations:
- The audio for earlier message will immediately cease taking part in as quickly because the consumer asks a brand new query.
- Any audio clips being performed by way of
useAudioPlayerwill immediately cease as quickly because the consumer disables the TTS setting.
This method additionally makes the audio system extra sturdy any we now have a single supply of fact for audio clips, and the chance to play a number of audio clips directly can be diminished.
This fixes #391
Reviewing a PR that provides Custom Provider Classes
I additionally reviewed a PR from Katie this week.
Right now, we simply should supported AI suppliers – OpenAI and OpenRouter. But since we expect to have extra sooner or later, it will grow to be impractical to handle all of them in a generic ChatCraftProvider class.
Katie is engaged on making a separate concrete class for every AI supplier inheriting from the present ChatCraftProvider class, such that if new suppliers do some issues otherwise, current strategies will be overridden and new strategies will be added to their very own lessons.
I went via the code and left a couple of feedback for adjustments. The PR continues to be up. If the PR continues to be up on the time of your studying, please have a look and tell us for those who can provide you with a greater method!
What’s Ahead 🔜
The TTS performance I’ve been engaged on nonetheless wants some extra work to make greatest use of the API OpenAI offers.
I’ll begin out by permitting the customers to select from completely different voices, potential to re-announce a message, and even downloading the audio narration of a response.
Everything is documented on this difficulty

Make TTS extra versatile
#400
- Add a Speak submenu to each human and bot messages
- In the Speak submenu permit one to pick out voice, which causes message to be spoken,
- as soon as message is spoke, permit generated message to be downloaded..can add a obtain to the converse submenu after speech completes. It’s ugly however undecided re different choices
- Changing voice in speech menu additionally adjustments it for the converse icon when automated tts is on
- ought to transfer converse icon to the menu on the left and alter it to be "choices" or 3 vertical dots on cellular
In this publish, I shared my method of making and managing an audio queue with a customized React Hook, and the way I’m leveraging it to stream OpenAI’s LLM responses to their TTS API, and in the end taking part in the generated clips so as.
I’ll comply with up concerning the different deliberate functionalities quickly.
In the meantime, STAY TUNED!
HI-FI News
by way of DEV Community https://dev.to
February 25, 2024 at 02:44AM
-
Product on sale
Audiophile Vinyl Records Cleaning BundleOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Product on sale
Easy Start Vinyl Records Cleaning KitOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Vinyl Records Cleaner Easy Groove Concentrate€34.95 incl. VAT -
Easy Groove Super Set€199.00 incl. VAT -
Easy Groove Enzycaster – vinyl records prewash cleaner€34.95 incl. VAT -
Easy Groove Extreme MK. II- vinyl records prewash cleaner€45.00 incl. VAT -
Vinyl Records Cleaner – Easy Groove Virgin Concentrate€35.00 incl. VAT -
Easy Groove Spray&Wipe vinyl records cleaner€34.95 incl. VAT









