This document provides detailed technical information about key systems in the Audio Program Generator.
The Audio Program Generator uses an intelligent caching system to avoid redundant API calls and speed up audio generation. The cache is stored in your browser's IndexedDB and persists across sessions.
- Storage Type: Browser IndexedDB (not filesystem)
- Database Name:
tts-cache - Object Store:
audio-snippets - Size Limit: 100 MB (automatically managed) file:///docs/IMPLEMENTATION.md#api-retry-mechanism
You can inspect the cache contents using your browser's DevTools:
- Open DevTools (F12 or Cmd+Option+I)
- Navigate to the Application tab (Chrome) or Storage tab (Firefox)
- Expand IndexedDB in the left sidebar
- Look for the
tts-cachedatabase - Click on
audio-snippetsobject store
Each cache entry contains:
- key: The unique cache identifier (e.g.,
tts_1a2b3c4d) - blob: The audio data (Blob object)
- timestamp: When the entry was cached
- size: Size in bytes
- text: The original phrase text (for reference)
Cache keys are generated using a hash of three components:
engine:text:optionsComponents:
- Engine: The TTS engine name (
openai,google-cloud,gtts) - Text: The exact phrase text
- Options: TTS-specific options (voice, speed, model, etc.), sorted alphabetically
Example:
openai:Stand upright and relax:{"format":"wav","model":"tts-1","speed":1,"voice":"nova"}
This is hashed to produce a cache key like: tts_1a2b3c4d
tts_<hash>
Where <hash> is a base-36 encoded hash of the combined string.
The cache system is smart about when to reuse existing audio. Here's what affects cache hits:
| Change | Cache Behavior | Reason |
|---|---|---|
| Phrase order changed | ✅ Reused | Each phrase is cached independently |
| Phrase durations changed | ✅ Reused | Duration only affects silence, not speech |
| Background music changed | ✅ Reused | Music is mixed separately, not cached |
| Export format changed (WAV/MP3) | ✅ Reused | Export format doesn't affect TTS generation |
| Same phrase appears multiple times | ✅ Reused | Same phrase = same cache key |
| Change | Cache Behavior | Reason |
|---|---|---|
| Phrase text changed | ❌ New generation | Text is part of cache key |
| TTS engine changed | ❌ New generation | Engine is part of cache key |
| Voice changed | ❌ New generation | Voice is in options (cache key) |
| Speed/rate changed | ❌ New generation | Speed is in options (cache key) |
| Model changed (OpenAI) | ❌ New generation | Model is in options (cache key) |
| Pitch changed (Google Cloud) | ❌ New generation | Pitch is in options (cache key) |
| Audio format changed | ❌ New generation | Format is in options (cache key) |
Original file:
Welcome; 3
Relax; 5
Breathe; 2
Reordered file:
Breathe; 2
Welcome; 3
Relax; 5
Result: ✅ All three phrases use cached audio. No API calls needed.
Original file:
Welcome; 3
Relax; 5
Changed durations:
Welcome; 10
Relax; 2
Result: ✅ Cached audio reused. Only the silence duration changes (no API calls).
Original settings:
- Voice: Nova
- Phrases: "Welcome", "Relax"
Changed settings:
- Voice: Shimmer
- Phrases: "Welcome", "Relax"
Result: ❌ Both phrases regenerated with new voice. Two API calls needed.
Cached phrases:
Welcome; 3
Relax; 5
New file:
Welcome; 3
Breathe; 2
Relax; 5
Result:
- ✅ "Welcome" - cached
- ❌ "Breathe" - new API call
- ✅ "Relax" - cached
Only one API call needed for the new phrase.
The cache automatically manages itself:
- Size limit: 100 MB maximum
- Eviction: Oldest entries removed when limit reached (LRU - Least Recently Used)
- Persistence: Survives browser restarts
Click the Clear Cache button in the Output section of the app to remove all cached audio.
To regenerate specific phrases:
- Clear the entire cache
- Regenerate your audio program
Or modify the phrase text slightly (e.g., add a space), generate, then change it back.
Cache statistics are shown in the browser console when the app loads:
📦 TTS Cache: 48 snippets, 2.17 MB
- Keep phrase text consistent: Even small changes (punctuation, capitalization) create new cache entries
- Reuse common phrases: Phrases like "Relax", "Breathe", etc. are cached once and reused
- Experiment with durations first: Change timing without regenerating audio
- Test background music: Try different music without affecting cached speech
Clear the cache when:
- Switching to a different voice permanently
- Changing TTS engines
- Testing new audio quality settings
- Cache grows too large (approaching 100 MB)
- Audio sounds corrupted or outdated
Typical sizes:
- Short phrase (1-3 words): ~30-50 KB
- Medium phrase (5-10 words): ~60-100 KB
- Long phrase (15+ words): ~120-200 KB
Example calculation:
- 50 unique phrases × 80 KB average = ~4 MB
- 100 unique phrases × 80 KB average = ~8 MB
The 100 MB limit allows for approximately 1,000-1,500 unique phrases.
function generateKey(text, engine, options) {
// Sort options for consistent keys
const optionsStr = JSON.stringify(options, Object.keys(options).sort());
const combined = `${engine}:${text}:${optionsStr}`;
// Simple hash function
let hash = 0;
for (let i = 0; i < combined.length; i++) {
const char = combined.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32-bit integer
}
return `tts_${Math.abs(hash).toString(36)}`;
}{
key: "tts_1a2b3c4d", // Unique identifier
blob: Blob, // Audio data
timestamp: 1699380000000, // Unix timestamp (ms)
size: 67244, // Size in bytes
text: "Stand upright and relax" // Original phrase (for debugging)
}Database: tts-cache (version 1)
ObjectStore: audio-snippets
KeyPath: key
Indexes:
- timestamp (non-unique)Symptoms: Every phrase regenerates, even unchanged ones
Solutions:
- Check browser console for cache errors
- Verify IndexedDB is enabled in browser settings
- Check if in private/incognito mode (cache may not persist)
- Clear browser data and restart
Symptoms: Browser storage warnings, slow performance
Solutions:
- Click "Clear Cache" button
- Reduce number of unique phrases
- Reuse common phrases across programs
Symptoms: Audio decode errors, playback failures
Solutions:
- Clear the cache completely
- Regenerate affected phrases
- Check browser console for specific errors
- Design for reusability: Create a library of common phrases
- Version your phrase files: Keep track of which phrases are cached
- Monitor cache size: Check console output periodically
- Clear strategically: Only clear when necessary (voice/engine changes)
- Test incrementally: Add new phrases gradually to maximize cache hits
- Implementation:
/scripts/services/TTSCacheService.js - Usage:
/scripts/controllers/AppController.js - Tests:
/tests/unit/TTSCacheService.test.js
The Audio Program Generator includes a robust retry mechanism to handle intermittent API failures, particularly for the OpenAI TTS API. This system automatically detects and recovers from empty responses, network issues, and temporary API instability.
When the OpenAI TTS API returns an empty response (0 bytes) despite a successful HTTP 200 status, the retry mechanism automatically:
- Detects the issue: Checks if the response buffer is empty
- Logs the problem: Records which phrase failed and response details
- Waits with backoff: Pauses before retrying (exponential backoff)
- Retries the request: Makes a new API call with identical parameters
- Validates the retry: Checks if the new response is valid
- Repeats if needed: Continues up to maximum retry attempts
- Caches on success: Stores successful result to avoid future retries
The system uses exponential backoff to avoid overwhelming the API:
| Attempt | Delay | Total Wait Time |
|---|---|---|
| Initial | 0ms | 0ms |
| Retry 1 | 1000ms (1s) | 1s |
| Retry 2 | 2000ms (2s) | 3s |
| Retry 3 | 3000ms (3s) | 6s |
Maximum retries: 3 attempts (4 total tries including initial)
- Reduces API load: Gives the API time to recover
- Avoids rate limiting: Prevents triggering rate limit protections
- Increases success rate: Temporary issues often resolve within seconds
- User-friendly: Total wait time (6s max) is acceptable for users
The retry mechanism provides detailed console logging to help diagnose issues:
🔄 Making OpenAI TTS API request: { text: "Welcome", model: "tts-1", voice: "nova", format: "wav" }
📡 API Response: { status: 200, statusText: "", ok: true, contentType: "audio/wav", contentLength: null, headers: [...] }
📥 Reading response as array buffer...
📥 Array buffer read complete: 67244 bytes
📦 Created blob: { size: 67244, type: "audio/wav" }
🔄 Making OpenAI TTS API request: { text: "Relax", model: "tts-1", voice: "nova", format: "wav" }
📡 API Response: { status: 200, statusText: "", ok: true, contentType: "audio/wav", contentLength: "0", headers: [...] }
📥 Reading response as array buffer...
📥 Array buffer read complete: 0 bytes
❌ OpenAI returned empty audio for: "Relax"
Response headers: [["content-type", "audio/wav"], ["content-length", "0"], ...]
⏳ Waiting 1000ms before retry 1/3...
🔄 Retry attempt 1/3...
📥 Retry 1 buffer size: 64244 bytes
✅ Retry 1 succeeded!
❌ OpenAI returned empty audio for: "Breathe deeply"
⏳ Waiting 1000ms before retry 1/3...
🔄 Retry attempt 1/3...
📥 Retry 1 buffer size: 0 bytes
⏳ Waiting 2000ms before retry 2/3...
🔄 Retry attempt 2/3...
📥 Retry 2 buffer size: 57044 bytes
✅ Retry 2 succeeded!
❌ OpenAI returned empty audio for: "Problematic phrase"
⏳ Waiting 1000ms before retry 1/3...
🔄 Retry attempt 1/3...
📥 Retry 1 buffer size: 0 bytes
⏳ Waiting 2000ms before retry 2/3...
🔄 Retry attempt 2/3...
📥 Retry 2 buffer size: 0 bytes
⏳ Waiting 3000ms before retry 3/3...
🔄 Retry attempt 3/3...
📥 Retry 3 buffer size: 0 bytes
❌ All retries failed for phrase: "Problematic phrase"
Error: OpenAI API returned empty audio for phrase: "Problematic phrase" even after 3 retries.
Retries are triggered when:
- Response status is 200 OK but buffer is empty (0 bytes)
- Response contains invalid audio data
- Network timeout or connection error
Retries are NOT triggered for:
- HTTP error responses (4xx, 5xx) - these fail immediately
- Invalid API key errors
- Rate limit errors (429) - these should be handled differently
- Valid audio responses (even if small)
- Empty response (0 bytes)
- Network timeouts
- Temporary API instability
- Invalid API key (401)
- Rate limit exceeded (429)
- Invalid request parameters (400)
- Server errors (500, 503)
- Time: Normal API response time (~1-3 seconds per phrase)
- API Calls: 1 per phrase
- User Experience: Seamless, no delays
- Time: +1 second delay for first retry
- API Calls: 2 per affected phrase
- User Experience: Minor delay, usually unnoticed
- Time: +6 seconds total delay (1s + 2s + 3s)
- API Calls: 4 per affected phrase
- User Experience: Noticeable but acceptable delay
The retry mechanism works seamlessly with the cache system:
- Check cache first: Before any API call
- API call with retry: If cache miss
- Cache on success: Store successful result (even from retry)
- Future requests: Use cached version (no retry needed)
Example flow:
Phrase: "Relax"
├─ Check cache → MISS
├─ API call → Empty response (0 bytes)
├─ Retry 1 (after 1s) → Success (64KB)
├─ Cache result → Stored
└─ Future requests → Cache HIT (no API call)
Current configuration (in OpenAITTSAdapter.js):
const maxRetries = 3;
const retryDelays = [1000, 2000, 3000]; // millisecondsThese values are optimized for:
- User experience: Total wait time acceptable
- API stability: Enough time for recovery
- Success rate: High probability of recovery within 3 retries
Based on testing with intermittent API issues:
| Metric | Value |
|---|---|
| Success rate (no retry) | ~85-90% |
| Success rate (with 1 retry) | ~95-98% |
| Success rate (with 2-3 retries) | ~99%+ |
| Average retry rate | ~10-15% of requests |
| Average delay per phrase | ~0.1-0.2 seconds |
Symptoms: Many phrases requiring retries (>30%)
Possible causes:
- OpenAI API experiencing widespread issues
- Network connectivity problems
- Rate limiting (too many requests too fast)
Solutions:
- Check OpenAI Status Page
- Reduce concurrent requests (generate fewer phrases at once)
- Check your internet connection
- Wait a few minutes and try again
Symptoms: All retries return empty responses
Possible causes:
- Specific phrase causing API issues
- API key quota exhausted
- API service degradation
Solutions:
- Try a different phrase to isolate the issue
- Check your OpenAI account usage/quota
- Try a different voice or model
- Contact OpenAI support if persistent
Symptoms: Errors occur but no retry logs appear
Possible causes:
- HTTP error response (not 200 OK)
- Request failing before response received
Solutions:
- Check for API key errors in console
- Verify network connectivity
- Check browser console for other errors
- Monitor console logs: Watch for retry patterns
- Clear cache if issues persist: Force fresh generation
- Report persistent failures: Note specific phrases that always fail
- Be patient: Allow retries to complete (up to 6 seconds)
- Check API status: Verify OpenAI service health during issues
- Implementation:
/scripts/services/OpenAITTSAdapter.js(lines 200-250) - Error handling:
/scripts/services/AudioService.js - Tests:
/tests/unit/OpenAITTSAdapter.test.js
The Audio Program Generator includes MP3 export functionality using the lamejs library, providing 7-10x file size reduction compared to WAV format while maintaining excellent audio quality.
Files involved:
index.html- Export format selector and bitrate controlsscripts/services/AudioService.js- MP3 encoding logicscripts/controllers/AppController.js- Export workflow
The system uses the lamejs library (loaded from CDN) to encode audio:
- Check library availability: Verify lamejs is loaded
- Convert audio format: Float32 samples → Int16 PCM
- Encode in chunks: Process 1152 samples per MP3 frame
- Report progress: Update UI every 10 blocks
- Yield to UI: Prevent browser freezing
- Create blob: Package encoded data
Users can choose between:
- WAV (uncompressed, large file) - For archival and editing
- MP3 (compressed, smaller file) - For distribution and playback
| Bitrate | Quality | File Size | Use Case |
|---|---|---|---|
| 128 kbps | Good | ~1 MB/min | Podcasts, voice-only |
| 192 kbps | Very Good | ~1.4 MB/min | Recommended default |
| 256 kbps | Excellent | ~1.9 MB/min | Music with speech |
| 320 kbps | Near-Perfect | ~2.4 MB/min | Audiophile quality |
For a 60-second meditation program with background music:
- WAV: 10.3 MB (uncompressed)
- MP3 @ 128 kbps: 960 KB (10.7x smaller)
- MP3 @ 192 kbps: 1.4 MB (7.4x smaller) ← Default
- MP3 @ 256 kbps: 1.9 MB (5.4x smaller)
- MP3 @ 320 kbps: 2.4 MB (4.3x smaller)
- Generate audio program (any TTS engine)
- Select export format (WAV or MP3)
- If MP3: Select quality (128/192/256/320 kbps)
- Click "Download Audio"
- See progress bar during encoding
- File downloads automatically
- Real-time progress bar during MP3 encoding
- Shows percentage complete (0-100%)
- Updates every ~10 blocks for smooth UI
- Yields to UI thread periodically to prevent freezing
The system includes an offline detection banner that:
- Appears when CDN resources fail to load
- Updates in real-time based on network status
- Provides one-click reload button when connection restored
- Works with inline CSS (no CDN dependency)
Scenario 1: Offline (library not cached)
- Error message with WAV fallback option
- Clear explanation of the issue
Scenario 2: Offline (library cached)
- MP3 encoding works perfectly
- No internet required
Scenario 3: Network drops during encoding
- Encoding continues successfully
- Library already loaded in memory
Scenario 4: Network restored
- Green banner with "Reload Now" button
- One-click to restore full functionality
MP3 encoder not available. This may be due to:
1. No internet connection (library not cached yet)
2. Browser blocking the script
3. Network error
Please check your connection and reload the page, or use WAV format instead.
- Graceful cancellation without error popup
- Progress bar shows "Encoding cancelled"
- No data loss
- ~2-5 seconds for 1 minute of audio (CPU-dependent)
- Single-threaded (JavaScript limitation)
- Yields to UI every 10 frames to prevent freezing
For 60-second stereo audio:
- AudioBuffer (in memory): 21 MB
- Int16 PCM conversion: 10.5 MB
- Encoder buffers: ~5 MB
- Peak memory usage: ~36 MB
- Final MP3 file (192 kbps): 1.4 MB
| Browser | lamejs Support | Caching | Performance |
|---|---|---|---|
| Chrome | ✅ | ✅ | Excellent |
| Edge | ✅ | ✅ | Excellent |
| Firefox | ✅ | ✅ | Good |
| Safari | ✅ | ✅ | Good |
CDN Caching:
- First load: Downloads ~50KB library
- Subsequent loads: Instant (cached)
- Works offline after first load
floatTo16BitPCM(input) {
const output = new Int16Array(input.length);
for (let i = 0; i < input.length; i++) {
// Clamp to -1.0 to 1.0
const s = Math.max(-1, Math.min(1, input[i]));
// Convert to 16-bit integer (-32768 to 32767)
output[i] = s < 0 ? s * 0x8000 : s * 0x7FFF;
}
return output;
}async audioBufferToMP3(buffer, bitrate = 192, onProgress = null) {
const mp3encoder = new lamejs.Mp3Encoder(channels, sampleRate, bitrate);
const mp3Data = [];
const blockSize = 1152; // MP3 frame size
for (let i = 0; i < samples; i += blockSize) {
// Check for cancellation
if (this.encodingCancelled) {
throw new Error('MP3 encoding cancelled by user');
}
// Encode chunk
const mp3buf = mp3encoder.encodeBuffer(leftChunk, rightChunk);
if (mp3buf.length > 0) {
mp3Data.push(new Int8Array(mp3buf));
}
// Report progress
if (onProgress) {
const progress = Math.floor((currentBlock / totalBlocks) * 100);
onProgress(progress);
}
// Yield to UI thread every 10 blocks
if (i % (blockSize * 10) === 0) {
await new Promise(resolve => setTimeout(resolve, 0));
}
}
// Flush encoder
const mp3buf = mp3encoder.flush();
if (mp3buf.length > 0) {
mp3Data.push(new Int8Array(mp3buf));
}
return new Blob(mp3Data, { type: 'audio/mp3' });
}- Encoding Speed: Slower than native FFmpeg (JavaScript vs C)
- Single-threaded: Can't use multiple CPU cores easily
- Memory Usage: Requires ~3x the final file size in RAM
- Browser Freeze: Very long files (>10 min) may cause brief UI freeze
For Users:
- Use 192 kbps for best quality/size balance
- Use WAV only if you need to edit the audio later
- First load requires internet (to download library)
- After first load, works completely offline
For Developers:
- Consider Web Workers for files >5 minutes
- Monitor memory usage for very long programs
- Add file size estimate before encoding
Potential improvements:
- Web Workers: Move encoding to background thread
- AAC/OGG Support: Add more codec options
- Variable Bitrate (VBR): Better quality/size tradeoff
- Metadata: Add ID3 tags (title, artist, etc.)
- Batch Export: Export multiple files at once
- Quality Preview: Let users hear sample before full export
- Implementation:
/scripts/services/AudioService.js(audioBufferToMP3 method) - UI:
/index.html(export format selector) - Controller:
/scripts/controllers/AppController.js(handleDownload method)
The Audio Program Generator supports OpenAI's TTS-1 and TTS-1-HD models as a text-to-speech engine option. OpenAI TTS provides high-quality voices with simple setup and pay-as-you-go pricing.
- Nova (Female - warm and friendly) - Recommended for meditation
- Shimmer (Female - soft and gentle) - Great for relaxation
- Alloy (Neutral - balanced)
- Echo (Male)
- Fable (Male - British)
- Onyx (Male - deep)
- TTS-1 (Standard): $15 per 1M characters
- TTS-1-HD (High Definition): $30 per 1M characters
- Speed: 0.25x to 4.0x (adjustable via slider)
- Format: WAV (for compatibility with mixing)
- ✅ Full audio export support
- ✅ Background music mixing
- ✅ Fade in/out effects
- ✅ API key validation
- ✅ Secure local storage of API key
- ✅ Pay-as-you-go pricing (no monthly fees)
The OpenAI TTS implementation follows the adapter pattern:
- Extends
TTSEngineAdapterbase class - Implements required methods:
getName(),getCapabilities(),generateSpeech(),validateApiKey() - Handles silence generation for phrase pauses
- Converts audio to WAV format for consistency
- Uses OpenAI's
/v1/audio/speechendpoint - Bearer token authentication
- Supports multiple audio formats (defaults to WAV)
- Proper error handling with descriptive messages
- API keys stored in localStorage:
openai-tts-api-key - Separate from Google Cloud API key
- Auto-loaded on page refresh
For 100K characters (typical usage):
| Provider | Cost | Setup Complexity |
|---|---|---|
| OpenAI TTS | $1.50 (standard) $3.00 (HD) |
⭐⭐⭐⭐⭐ Simple |
| Google Cloud | $0.00 (free tier) $1.60 (after) |
⭐⭐ Complex |
| Web Speech API | $0.00 | ⭐⭐⭐⭐⭐ None (limited) |
- Simple Setup: No billing account complexities like Google Cloud
- Predictable Costs: Pay only for what you use, no monthly fees
- High Quality: Excellent voice quality comparable to Google Cloud
- Flexibility: 6 voices to choose from, speed control
- Full Features: Export, mixing, and all advanced features supported
/scripts/services/OpenAITTSAdapter.js
- Implements the
TTSEngineAdapterinterface - Supports TTS-1 (standard) and TTS-1-HD (high quality) models
- 6 preset voices with descriptions
- Speed control (0.25x - 4.0x)
- Returns WAV audio blobs for mixing and export
/scripts/services/TTSService.js
- Added OpenAI adapter to the adapters registry
- Enhanced
loadApiKey()to load OpenAI API key from localStorage - Enhanced
saveApiKey()to support multiple engines
/scripts/controllers/AppController.js
- Added OpenAI settings UI visibility toggle
- Enhanced
handleSaveApiKey()to support both Google Cloud and OpenAI - Added OpenAI API key loading
- Added OpenAI TTS generation logic
- Added OpenAI speed slider to value display setup
/index.html
- Added "OpenAI TTS" option to engine dropdown
- Created OpenAI settings section with:
- API key input field with save button
- Voice selector (6 voices with descriptions)
- Model quality selector (tts-1 vs tts-1-hd)
- Speed slider (0.25x - 4.0x)
POST https://api.openai.com/v1/audio/speech
Headers:
Authorization: Bearer sk-...
Content-Type: application/json
Body:
{
"model": "tts-1",
"input": "Welcome to your audio program",
"voice": "nova",
"response_format": "wav",
"speed": 1.0
}- Binary audio data (WAV format)
- Content-Type: audio/wav
- Typical size: 50-150 KB per phrase
OpenAI API error: Incorrect API key provided
OpenAI API error: You exceeded your current quota
Failed to generate speech: Network error
- Set usage limits: Configure monthly budget in OpenAI dashboard
- Use standard model: TTS-1 is sufficient for most use cases
- Cache aggressively: Leverage the caching system to minimize API calls
- Monitor costs: Check OpenAI dashboard regularly
- Add support for
voice_instructionsparameter (the "vibe" feature) - Add emotion/tone controls
- Add accent customization
- Implement advanced voice customization UI
- Add usage tracking/cost estimation
- Add voice preview samples
- Add batch generation optimization
- OpenAI API is separate from ChatGPT Plus subscription
- API keys are stored locally (never sent to our servers)
- Users should set usage limits in OpenAI dashboard
- Standard model (TTS-1) is recommended for most use cases
- HD model (TTS-1-HD) is only needed for highest quality requirements
- Implementation:
/scripts/services/OpenAITTSAdapter.js - Service:
/scripts/services/TTSService.js - Controller:
/scripts/controllers/AppController.js - Tests:
/tests/unit/OpenAITTSAdapter.test.js
The Project Cache System automatically saves your audio projects (phrase files, background music, and all settings) so you can quickly restore them when you return to the app. This eliminates the need to re-upload files and reconfigure settings for projects you work on frequently.
When you successfully generate audio, the system automatically saves:
- Phrase file content - The text of all your phrases
- Background music - The audio file (if used)
- TTS settings - Engine, voice, speed, pitch, etc.
- Export settings - Format (WAV/MP3) and bitrate
The next time you visit the app, your recent projects appear at the top of the page, ready to restore with one click.
Location: Browser IndexedDB
- Database name:
apg-projects - Object store:
projects - Max projects: 10 (automatically prunes oldest)
What's stored per project:
{
id: "project_1699380000000_abc123",
name: "morning-meditation.txt",
phraseFileContent: "Welcome; 3\nRelax; 5\n...",
backgroundMusic: Blob, // Audio file
backgroundMusicName: "calm-music.mp3",
ttsEngine: "openai",
ttsOptions: { voice: "nova", model: "tts-1", speed: 1.0 },
exportSettings: { format: "mp3", bitrate: 192 },
timestamp: 1699380000000
}When you have saved projects, a "Recent Projects" section appears at the top of the page showing:
- Project name (from phrase file name)
- Time saved ("Just now", "2 hours ago", "3 days ago", etc.)
- TTS engine used
- Background music status
- Restore button - One-click to load all settings
- Delete button (×) - Remove individual projects
Projects are automatically saved after successful audio generation. No user action required!
Click the "Restore" button on any project card:
- Phrase file is loaded
- Background music is loaded (if used)
- TTS engine is selected
- All voice/speed/pitch settings are restored
- Export format and bitrate are restored
- Click "Generate Audio" to recreate the project
Key benefit: TTS snippets are already cached, so regeneration is fast (2-5 seconds instead of 30+ seconds)!
- System keeps the 10 most recent projects
- Older projects are automatically deleted
- Pruning happens after each save
- Clear All button: Removes all saved projects
- Individual delete (×): Remove specific projects
- Confirmation dialog prevents accidental deletion
Typical project sizes:
- Phrase file: ~1-5 KB (text)
- Background music: ~3-10 MB (audio file)
- Settings: ~1 KB (JSON)
- Total per project: ~3-10 MB
10 projects: ~30-100 MB total
Without Project Cache:
- Upload phrase file
- Upload background music
- Select TTS engine
- Configure voice/speed/pitch
- Set export format
- Generate audio (30+ seconds)
With Project Cache:
- Click "Restore"
- Click "Generate Audio" (2-5 seconds with TTS cache)
Time saved: ~90% for repeat projects
- Iterative refinement: Tweak phrases, regenerate quickly
- Multiple versions: Try different voices/speeds
- Daily routines: Morning meditation, evening relaxation
- Template projects: Reuse structure with new content
- A/B testing: Compare different background music
The Project Cache works seamlessly with the TTS Cache:
First generation (no caches):
- TTS API calls: 10 phrases = 10 API calls
- Time: ~30 seconds
- Project saved automatically
Restore and regenerate (TTS cached):
- TTS API calls: 0 (all cached!)
- Time: ~2-5 seconds (just mixing)
- Fast iteration on settings
Change one phrase:
- TTS API calls: 1 (only the changed phrase)
- Time: ~5 seconds
- Other phrases use cache
generateId() {
return `project_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
// Example: "project_1699380000000_k3j2h5g9"formatTimestamp(timestamp) {
const diffMins = Math.floor((now - timestamp) / 60000);
if (diffMins < 1) return 'Just now';
if (diffMins < 60) return `${diffMins} min ago`;
if (diffHours < 24) return `${diffHours} hour(s) ago`;
if (diffDays < 7) return `${diffDays} day(s) ago`;
return date.toLocaleDateString();
}Uses the DataTransfer API to programmatically set file inputs:
const dataTransfer = new DataTransfer();
dataTransfer.items.add(phraseFile);
phraseInput.files = dataTransfer.files;💼 Projects: 3 saved, 25.4 MB
💾 Saved project: "morning-meditation.txt"
🔄 Restoring project: "morning-meditation.txt"
🧹 Pruning 1 old project(s)...
🗑️ Deleted project: project_1699380000000_abc123
| Browser | IndexedDB Support | DataTransfer API | Status |
|---|---|---|---|
| Chrome | ✅ | ✅ | Full support |
| Edge | ✅ | ✅ | Full support |
| Firefox | ✅ | ✅ | Full support |
| Safari | ✅ | ✅ | Full support |
All modern browsers fully support the required APIs.
- Browser-specific: Projects are stored per browser, not synced across devices
- Origin-specific: localhost and deployed site have separate storage
- No cloud sync: Projects are local only
- 10 project limit: Older projects are automatically deleted
- No export/import: Can't share projects between browsers (yet)
- Local storage only: Projects never leave your browser
- No server upload: All data stays on your device
- User control: Easy to delete individual or all projects
- No tracking: System doesn't track what you create
Potential improvements:
- Export/Import: Save projects as files, share between devices
- Cloud sync: Optional sync across browsers/devices
- Project folders: Organize projects into categories
- Search/filter: Find projects by name or date
- Project notes: Add descriptions or tags
- Unlimited storage: Remove 10-project limit with pagination
- Duplicate project: Clone and modify existing projects
- Project templates: Pre-made structures for common use cases
Symptoms: No "Recent Projects" section visible
Possible causes:
- No projects saved yet (generate audio first)
- Browser in private/incognito mode
- IndexedDB disabled in browser settings
Solutions:
- Generate an audio project first
- Check browser console for errors
- Verify IndexedDB is enabled
Symptoms: Click "Restore" but files don't load
Possible causes:
- Browser security restrictions
- Corrupted project data
Solutions:
- Try deleting and recreating the project
- Check browser console for errors
- Clear all projects and start fresh
Symptoms: Warning about storage limits
Solutions:
- Click "Clear All" to remove all projects
- Delete individual old projects
- Use smaller background music files
- Name files clearly: Use descriptive phrase file names (they become project names)
- Regular cleanup: Delete projects you no longer need
- Test restore: Verify projects restore correctly before relying on them
- Backup important projects: Download the final audio for safekeeping
- Use TTS cache: Let both caches work together for maximum speed
- Implementation:
/scripts/services/ProjectCacheService.js - Controller:
/scripts/controllers/AppController.js(project methods) - UI:
/index.html(Recent Projects section)