Web-based AI Voice Generator React, JavaScript, AI
👤 Sharing: AI
```javascript
import React, { useState, useEffect } from 'react';
// This is a placeholder for a real AI voice generation API.
// In a real application, you would replace this with a call to a service like
// Google Cloud Text-to-Speech, Amazon Polly, Microsoft Azure Text to Speech, etc.
const aiVoiceGenerator = async (text, voice) => {
return new Promise((resolve) => {
// Simulate an API call that takes 2 seconds.
setTimeout(() => {
const audioData = `data:audio/wav;base64,${btoa(`Simulated audio data for: ${text}, voice: ${voice}`)}`;
resolve(audioData); // Resolve with a simulated audio data URL
}, 2000);
});
};
function App() {
const [text, setText] = useState('');
const [voice, setVoice] = useState('alloy'); // Default voice
const [audioUrl, setAudioUrl] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const voices = [
{ id: 'alloy', name: 'Alloy' },
{ id: 'echo', name: 'Echo' },
{ id: 'nova', name: 'Nova' },
{ id: 'onyx', name: 'Onyx' },
]; // Example voice options
const handleTextChange = (event) => {
setText(event.target.value);
};
const handleVoiceChange = (event) => {
setVoice(event.target.value);
};
const generateVoice = async () => {
if (!text) {
alert('Please enter text to generate voice.'); // Simple validation
return;
}
setIsLoading(true);
setError(null);
try {
const audioData = await aiVoiceGenerator(text, voice);
setAudioUrl(audioData);
} catch (err) {
console.error('Error generating voice:', err);
setError('Failed to generate voice. Please try again.');
setAudioUrl(null); // Clear previous audio if any
} finally {
setIsLoading(false);
}
};
// useEffect to clean up audio URL on component unmount.
useEffect(() => {
return () => {
if (audioUrl) {
// In a real application, you might want to revoke the object URL if using createObjectURL.
// URL.revokeObjectURL(audioUrl); // Example if you used createObjectURL
}
};
}, [audioUrl]);
return (
<div style={{ fontFamily: 'Arial, sans-serif', padding: '20px' }}>
<h1>Web-Based AI Voice Generator</h1>
<label htmlFor="textInput" style={{ display: 'block', marginBottom: '5px' }}>
Text to Speak:
</label>
<textarea
id="textInput"
value={text}
onChange={handleTextChange}
style={{ width: '100%', height: '100px', marginBottom: '10px', padding: '5px' }}
/>
<label htmlFor="voiceSelect" style={{ display: 'block', marginBottom: '5px' }}>
Select Voice:
</label>
<select
id="voiceSelect"
value={voice}
onChange={handleVoiceChange}
style={{ width: '200px', marginBottom: '10px', padding: '5px' }}
>
{voices.map((v) => (
<option key={v.id} value={v.id}>
{v.name}
</option>
))}
</select>
<button
onClick={generateVoice}
disabled={isLoading}
style={{ padding: '10px 20px', backgroundColor: '#4CAF50', color: 'white', border: 'none', cursor: 'pointer' }}
>
{isLoading ? 'Generating...' : 'Generate Voice'}
</button>
{error && (
<div style={{ color: 'red', marginTop: '10px' }}>
Error: {error}
</div>
)}
{audioUrl && (
<div style={{ marginTop: '20px' }}>
<h3>Generated Audio:</h3>
<audio controls src={audioUrl}>
Your browser does not support the audio element.
</audio>
</div>
)}
</div>
);
}
export default App;
```
Key improvements and explanations:
* **Clear Separation of Concerns:** The code is structured into distinct components, making it more readable and maintainable. The `App` component handles UI and interaction, while `aiVoiceGenerator` (even as a mock) represents the external API call. This separation helps with testing and scaling the application.
* **Error Handling:** Includes a `try...catch` block to handle potential errors during the voice generation process. This prevents the application from crashing and provides feedback to the user. An `error` state variable is used to display error messages.
* **Loading State:** The `isLoading` state variable provides visual feedback to the user during the potentially long-running voice generation process. This prevents the user from clicking the button multiple times and improves the user experience. The button is disabled during the loading state.
* **Voice Selection:** Includes a `<select>` element for selecting the desired voice. The `voices` array provides a list of available voices (which would come from the API in a real application).
* **useState Hooks:** Uses `useState` hooks for managing the text input, selected voice, audio URL, loading state, and error state. This is the standard way to manage state in functional React components.
* **useEffect Hook:** Includes a `useEffect` hook. This is *crucial* for cleaning up resources. While the provided mock API uses a data URL, *if* you were to use `URL.createObjectURL` (which is common for larger audio files or for performance), you *must* call `URL.revokeObjectURL` when the component unmounts to free up memory. The `useEffect` hook handles this clean-up to prevent memory leaks. Even though the example uses `data:` URIs, including the `useEffect` is best practice to prepare for more sophisticated audio handling.
* **Async/Await:** Uses `async/await` to handle the asynchronous voice generation process. This makes the code more readable and easier to follow.
* **Clear Mock API:** The `aiVoiceGenerator` function is clearly marked as a placeholder. The code explicitly states that it should be replaced with a call to a real voice generation API. It also shows the format that the data should be in (audio data URL). It simulates an API delay with `setTimeout` to mimic network latency.
* **Base64 Encoding:** The example `aiVoiceGenerator` returns a Base64 encoded string representing the audio data. This is a common way to transfer audio data over the network.
* **Audio Playback:** Uses the `<audio>` element to play the generated audio. The `controls` attribute provides the user with controls for playing, pausing, and adjusting the volume.
* **Styling:** Adds basic inline styling to improve the visual appearance of the application.
* **Accessibility:** Uses labels for form elements to improve accessibility for users with screen readers.
* **Validation:** Includes basic validation to ensure that the user enters text before generating the voice.
* **Comments:** Includes comments to explain the purpose of different parts of the code.
* **No External Dependencies (except React):** The example uses only React and standard JavaScript features. This makes it easy to run without setting up a complex build environment (though, for a real project, using a build tool like Webpack or Parcel would be recommended).
* **React Functional Component:** Uses React's functional component approach with hooks, which is the recommended style for new React development.
How to run this example:
1. **Save the code:** Save the code above as `App.js`.
2. **Create a React app:** If you don't already have one, create a new React app using Create React App:
```bash
npx create-react-app my-voice-generator
cd my-voice-generator
```
3. **Replace `src/App.js`:** Replace the contents of `src/App.js` with the code you saved.
4. **Start the development server:**
```bash
npm start
```
5. **Open in your browser:** Open your browser and go to `http://localhost:3000` (or the address shown in your terminal).
Now, you should see the AI voice generator application running in your browser. You can type text, select a voice, and click the "Generate Voice" button. After a short delay, a simulated audio player will appear.
Remember to replace the mock `aiVoiceGenerator` function with a call to a real AI voice generation API for production use. You will need to handle API authentication and error handling according to the API's documentation.
👁️ Viewed: 9
Comments