### Usage Example: Get and Use Voices on Windows Source: https://github.com/marak/say.js/blob/master/_autodocs/api-reference/Say-class.md Demonstrates how to get installed voices on Windows and use the first available voice for speech. Includes error handling and platform checking. ```javascript const say = require('say') // Get available voices on Windows if (process.platform === 'win32') { say.getInstalledVoices((err, voices) => { if (err) { return console.error('Failed to get voices:', err) } console.log('Available voices:', voices) // Example output: ['Microsoft Zira Desktop', 'Microsoft David Desktop'] // Use the first voice if (voices.length > 0) { say.speak('Hello', voices[0], 1.0) } }) } else { console.log('getInstalledVoices() only works on Windows') } ``` -------------------------------- ### Basic Speech Synthesis Example Source: https://github.com/marak/say.js/blob/master/_autodocs/COMPLETION-REPORT.txt Demonstrates the basic usage of the speak method to synthesize speech. Ensure the 'say' library is installed and imported. ```javascript const say = require('say'); say.speak("Hello world"); ``` -------------------------------- ### Say.js Linux Usage Example Source: https://github.com/marak/say.js/blob/master/_autodocs/api-reference/platform-implementations.md Demonstrates how to initialize and use the Say.js library for the Linux platform. Includes examples for speaking text with the default voice and a specified voice. ```javascript const { Say } = require('say') const say = new Say('linux') // Speak with default Festival voice say.speak('Hello Linux', undefined, 1.0, (err) => { if (err) console.error(err) }) // Speak with specified voice (voice_kal_diphone is the standard available voice) say.speak('Testing', 'voice_kal_diphone', 0.8, (err) => { if (err) console.error(err) }) ``` -------------------------------- ### Usage Example: Speak with Each Installed Voice Source: https://github.com/marak/say.js/blob/master/_autodocs/api-reference/Say-class.md Iterates through all installed voices and speaks a message with each one, spaced out by a delay. This example assumes voices are available and handles potential errors by doing nothing. ```javascript say.getInstalledVoices((err, voices) => { if (err) return voices.forEach((voice, index) => { setTimeout(() => { say.speak(`Testing voice: ${voice}`, voice, 1.0) }, index * 3000) // Space out the speeches }) }) ``` -------------------------------- ### Linux Specific Speech Setup and Usage Source: https://github.com/marak/say.js/blob/master/_autodocs/INDEX.md Demonstrates how to create a Say instance for Linux and speak text. Requires festival and festvox-kallpc16k to be installed. ```bash sudo apt-get install festival festvox-kallpc16k ``` ```javascript const { Say } = require('say') const say = new Say('linux') say.speak('Hello Linux', null, 1.0) ``` -------------------------------- ### Say.js macOS Usage Example Source: https://github.com/marak/say.js/blob/master/_autodocs/api-reference/platform-implementations.md Example demonstrating how to initialize Say.js for macOS and use its 'speak' and 'export' methods. Includes basic error handling. ```javascript const { Say } = require('say') const say = new Say('darwin') // Speak with Alex voice at half speed say.speak('Hello macOS', 'Alex', 0.5, (err) => { if (err) console.error(err) }) // Export to file say.export('Save this', 'Victoria', 1.0, 'output.wav', (err) => { if (err) console.error(err) }) ``` -------------------------------- ### Say.js Usage Example for Windows Source: https://github.com/marak/say.js/blob/master/_autodocs/api-reference/platform-implementations.md Demonstrates how to use the Say.js library with the 'win32' platform implementation. Includes examples for listing available voices, speaking text with a specific voice, and exporting speech to a WAV file. ```javascript const { Say } = require('say') const say = new Say('win32') // List available voices say.getInstalledVoices((err, voices) => { if (err) return console.error(err) console.log('Available voices:', voices) // Example: ['Microsoft Zira Desktop', 'Microsoft David Desktop'] }) // Speak with specific voice say.speak('Hello Windows', 'Microsoft Zira Desktop', 1.0, (err) => { if (err) console.error(err) }) // Export to WAV file say.export('Audio content', null, 1.5, 'output.wav', (err) => { if (err) console.error(err) else console.log('File created: output.wav') }) ``` -------------------------------- ### Get Installed Voices Source: https://github.com/marak/say.js/blob/master/_autodocs/COMPLETION-REPORT.txt Demonstrates how to retrieve a list of all installed voices on the system. The callback receives an error object and an array of voice names. ```javascript const say = require('say'); say.getInstalledVoices(function(err, voices) { if (err) { console.error("Error getting voices:", err); return; } console.log("Installed voices:", voices); }); ``` -------------------------------- ### Say Class Usage Example Source: https://github.com/marak/say.js/blob/master/_autodocs/api-reference/Say-class.md Demonstrates how to instantiate the Say class and use its speak method. Includes an example of handling unsupported platforms. ```javascript const { Say } = require('say') // Use auto-detected platform const say = new Say() say.speak('Hello world') // Override platform for testing try { const winSay = new Say('win32') } catch (err) { console.error('Unsupported platform:', err.message) } ``` -------------------------------- ### Install Say.js with npm Source: https://github.com/marak/say.js/blob/master/README.md Use npm to install the Say.js package. ```bash npm install say ``` -------------------------------- ### Explicit Platform Instantiation Source: https://github.com/marak/say.js/blob/master/_autodocs/ARCHITECTURE.md Provides an example of how to create a Say instance with an explicitly specified platform, bypassing the default load-time detection. ```javascript const { Say } = require('say') const say = new Say('win32') // Explicit platform ``` -------------------------------- ### Install Festival on Linux Source: https://github.com/marak/say.js/blob/master/_autodocs/GETTING-STARTED.md Provides the commands to install the Festival text-to-speech engine on Linux systems if it's missing. ```bash sudo apt-get update sudo apt-get install festival festvox-kallpc16k ``` -------------------------------- ### Speak on Windows Source: https://github.com/marak/say.js/blob/master/_autodocs/GETTING-STARTED.md Use say.js on Windows, leveraging PowerShell and SAPI. Supports getting installed voices and exporting to WAV. ```javascript const say = require('say') // Uses PowerShell and SAPI say.speak('Hello Windows', 'Microsoft Zira Desktop', 1.0) // Get list of installed voices (Windows only) say.getInstalledVoices((err, voices) => { if (err) console.error(err) else console.log('Available voices:', voices) }) // Export to WAV file (Windows only) say.export('Audio content', 'Microsoft David Desktop', 1.0, 'output.wav', (err) => { if (err) console.error(err) }) ``` -------------------------------- ### Say.js Get Installed Voices Method Signature Source: https://github.com/marak/say.js/blob/master/README.md Signature for the getInstalledVoices method, which takes a callback to return a list of available voices. ```javascript say.getInstalledVoices(callback) ``` -------------------------------- ### macOS Say Command Example Source: https://github.com/marak/say.js/blob/master/_autodocs/ARCHITECTURE.md Demonstrates how to use the built-in 'say' command on macOS for normal speech output and exporting audio to a WAV file. ```bash # Normal speech say -v Alex -r 87 "Hello" # Export to file say -v Samantha -r 131 -o output.wav --data-format=LEF32@32000 "Hello" ``` -------------------------------- ### Say.js Usage Examples Source: https://github.com/marak/say.js/blob/master/_autodocs/MODULE-GRAPH.md Illustrates common ways to import and use the Say.js library, including the singleton instance, the Say class, and platform constants. ```javascript // Singleton (most common) const say = require('say') say.speak('Hello') // Class const { Say } = require('say') const customSay = new Say('darwin') // Platform constants const { platforms } = require('say') const say = new Say(platforms.LINUX) ``` -------------------------------- ### JavaScript Usage Example for errorCallback Source: https://github.com/marak/say.js/blob/master/_autodocs/types.md Demonstrates how to use the errorCallback for handling asynchronous operations like speaking text or getting installed voices. Note the different callback signatures for different functions. ```javascript const say = require('say') // Using errorCallback function handleComplete(err) { if (err) { console.error('Operation failed:', err) } else { console.log('Operation completed') } } say.speak('Hello', null, 1.0, handleComplete) // For getInstalledVoices, the callback receives a second parameter function handleVoices(err, voices) { if (err) { console.error('Failed to get voices:', err) } else { console.log('Voices:', voices) // voices is Array } } say.getInstalledVoices(handleVoices) ``` -------------------------------- ### one-time Usage Example Source: https://github.com/marak/say.js/blob/master/_autodocs/ARCHITECTURE.md Demonstrates how to use the 'one-time' npm package to ensure a callback function is executed at most once. ```javascript const once = require('one-time') const safeCallback = once(userCallback) // Now safeCallback fires max once, regardless of how many times called ``` -------------------------------- ### Linux Festival Scheme Example Source: https://github.com/marak/say.js/blob/master/_autodocs/ARCHITECTURE.md Shows how to control the 'festival' TTS system on Linux using Scheme commands piped via stdin for audio playback. ```scheme (Parameter.set 'Audio_Command "aplay -q -c 1 -t raw -f s16 -r $(($SR*100/100)) $FILE") (voice_kal_diphone) (SayText "Hello") ``` -------------------------------- ### macOS buildSpeakCommand Example Source: https://github.com/marak/say.js/blob/master/_autodocs/ARCHITECTURE.md Illustrates the structure of the command and arguments returned by the platform-specific buildSpeakCommand function for macOS. This is used to spawn the child process for text-to-speech. ```json { "command": "say", "args": ["-v", "Alex", "Hello", "-r", "87"], "pipedData": "", "options": {} } ``` -------------------------------- ### say.getInstalledVoices() Source: https://github.com/marak/say.js/blob/master/README.md Retrieves a list of all installed voices on the system. A callback is required to receive the list. ```APIDOC ## getInstalledVoices() ### Description Retrieves a list of all installed voices on the system. A callback is required to receive the list. ### Method ```javascript say.getInstalledVoices(callback) ``` ### Parameters * **callback** (function) - Required - A function that will be called with the list of installed voices. The callback receives an error object as the first argument and an array of voice objects as the second argument. ``` -------------------------------- ### Get Available Voices and Engine Source: https://github.com/marak/say.js/wiki/Proposed-1.0-API Retrieves a list of available voices and the current speech synthesis engine. No setup is required beyond importing the 'say' module. ```javascript var Say = require('say'); console.log(Say.voices()); // ['Samantha', 'Alex', ...]; console.log(Say.engine()); // 'say' || 'espeak' || 'festival' || 'api' ``` -------------------------------- ### Platform-Specific Voice Selection (Windows) Source: https://github.com/marak/say.js/blob/master/_autodocs/COMPLETION-REPORT.txt Example of selecting a specific voice on Windows. Voice names are dependent on installed Windows voices (SAPI). ```javascript const say = require('say'); // Example voice name for Windows, actual names may vary const winVoice = 'Microsoft Zira Desktop'; say.speak('This is a Windows specific voice.', winVoice, 1.0, function(err) { if (err) { console.error('Error speaking on Windows:', err); } }); ``` -------------------------------- ### Basic TypeScript Usage Source: https://github.com/marak/say.js/blob/master/_autodocs/GETTING-STARTED.md Demonstrates the fundamental way to use the say.js library in TypeScript for text-to-speech. Ensure you have the 'say' package installed. ```typescript import say from 'say' // Basic usage say.speak('Hello TypeScript', 'Alex', 1.0, (err) => { if (err) console.error(err) }) ``` -------------------------------- ### List and Use Voices on Windows Source: https://github.com/marak/say.js/blob/master/_autodocs/INDEX.md Shows how to retrieve and use installed voices on Windows. It fetches voices, logs the first available voice, and then speaks a message using that voice. ```javascript const say = require('say') if (process.platform === 'win32') { say.getInstalledVoices((err, voices) => { if (err) console.error(err) else if (voices.length > 0) { console.log('Using voice:', voices[0]) say.speak('Hello', voices[0], 1.0) } }) } ``` -------------------------------- ### Install Festival on Linux Source: https://github.com/marak/say.js/blob/master/README.md Command to install the Festival speech synthesis system and a default voice on Debian/Ubuntu-based Linux systems. ```sh sudo apt-get install festival festvox-kallpc16k ``` -------------------------------- ### Platform-Specific Voice Selection (Linux) Source: https://github.com/marak/say.js/blob/master/_autodocs/COMPLETION-REPORT.txt Example of selecting a specific voice on Linux. Voice names and availability depend on the installed speech synthesis engines (e.g., espeak). ```javascript const say = require('say'); // Example voice name for Linux (espeak), actual names may vary const linuxVoice = 'english-us'; say.speak('This is a Linux specific voice.', linuxVoice, 1.0, function(err) { if (err) { console.error('Error speaking on Linux:', err); } }); ``` -------------------------------- ### getInstalledVoices(callback) Source: https://github.com/marak/say.js/blob/master/_autodocs/COMPLETION-REPORT.txt Retrieves a list of all voices installed on the system that can be used for speech synthesis. ```APIDOC ## getInstalledVoices(callback) ### Description Retrieves a list of all voices installed on the system that can be used for speech synthesis. This allows users to select specific voices. ### Method `getInstalledVoices` ### Parameters #### Parameters - **callback** (function) - Required - A callback function that will be executed with the list of available voices. The callback receives two arguments: an error object (if an error occurred, otherwise null) and an array of voice objects. ### Return Type This method operates asynchronously, invoking the callback with an array of voice objects. Each voice object typically contains properties like `name` and `id`. ``` -------------------------------- ### Async/Await with Promisified Say Function Source: https://github.com/marak/say.js/blob/master/_autodocs/GETTING-STARTED.md This example demonstrates how to use async/await with Say.js by promisifying the speak function. It requires the 'util' module for promisification. ```javascript const say = require('say') const util = require('util') const speak = util.promisify((text, voice, speed, callback) => { say.speak(text, voice, speed, callback) }) async function demo() { try { await speak('Hello', null, 1.0) await speak('World', null, 1.0) console.log('Done') } catch (err) { console.error('Error:', err) } } demo() ``` -------------------------------- ### Factory Pattern: Explicit Instance Creation Source: https://github.com/marak/say.js/blob/master/_autodocs/ARCHITECTURE.md This example shows the Factory pattern, allowing users to explicitly create new instances of Say and optionally override the detected platform. ```javascript // Alternative: User explicitly creates instances const { Say } = require('say') const customSay = new Say('win32') // Override platform ``` -------------------------------- ### TypeScript Usage Example Source: https://github.com/marak/say.js/blob/master/_autodocs/COMPLETION-REPORT.txt Shows how to use the Say.js library with TypeScript, leveraging the provided type definitions for better code completion and type safety. ```typescript import * as say from 'say'; const textToSpeak: string = "Hello from TypeScript!"; const voice: string = 'Alex'; // Example voice const speed: number = 1.0; say.speak(textToSpeak, voice, speed, (err?: Error) => { if (err) { console.error("Error speaking in TypeScript:", err); } else { console.log("TypeScript speech finished."); } }); ``` -------------------------------- ### Speak on Linux Source: https://github.com/marak/say.js/blob/master/_autodocs/GETTING-STARTED.md Use the Say class for Linux, requiring Festival to be installed. Export is not supported on Linux. ```javascript const { Say } = require('say') const say = new Say('linux') // Requires Festival to be installed say.speak('Hello Linux', null, 1.0) // Note: export() is not supported on Linux // Note: getInstalledVoices() is not supported on Linux ``` -------------------------------- ### Say.js speak using modern async/await Source: https://github.com/marak/say.js/blob/master/_autodocs/api-reference/Say-class.md Provides an example of how to wrap the `say.speak` method in a Promise to enable usage with modern JavaScript `async/await` syntax for cleaner asynchronous code. ```javascript // Using modern async wrapper function speak(text, voice, speed) { return new Promise((resolve, reject) => { say.speak(text, voice, speed, (err) => { if (err) reject(err) else resolve() }) }) } await speak('Async example', 'Samantha', 1.0) ``` -------------------------------- ### Say Instance Methods Source: https://github.com/marak/say.js/blob/master/_autodocs/MODULE-GRAPH.md The Say instance, exported as the default module, provides core functionalities for text-to-speech. These include speaking text, stopping ongoing speech, and retrieving installed voices. ```APIDOC ## say.speak() ### Description Initiates text-to-speech playback. ### Method `speak(text, callback)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **text** (string) - Required - The text to be spoken. - **callback** (function) - Optional - A callback function to be executed after speech playback completes or is interrupted. ### Request Example ```javascript const say = require('say'); say.speak('Hello, world!', (err) => { if (err) { console.error('Error speaking:', err); } }); ``` ### Response #### Success Response (void) No explicit return value on success, but the callback is invoked. #### Response Example N/A ``` ```APIDOC ## say.stop() ### Description Stops any ongoing text-to-speech playback. ### Method `stop(callback)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **callback** (function) - Optional - A callback function to be executed after speech playback is stopped. ### Request Example ```javascript const say = require('say'); say.stop((err) => { if (err) { console.error('Error stopping speech:', err); } }); ``` ### Response #### Success Response (void) No explicit return value on success, but the callback is invoked. #### Response Example N/A ``` ```APIDOC ## say.getInstalledVoices() ### Description Retrieves a list of all installed voices available on the system. ### Method `getInstalledVoices(callback)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **callback** (function) - Required - A callback function that receives an error (if any) and an array of voice objects. ### Request Example ```javascript const say = require('say'); say.getInstalledVoices((err, voices) => { if (err) { console.error('Error getting voices:', err); } else { console.log('Installed voices:', voices); } }); ``` ### Response #### Success Response (Array) An array of objects, where each object represents an installed voice. #### Response Example ```json [ { "name": "VoiceName1", "id": "voice-id-1", "lang": "en-US" }, { "name": "VoiceName2", "id": "voice-id-2", "lang": "en-GB" } ] ``` ``` -------------------------------- ### Windows Specific Speech and Voice Listing Source: https://github.com/marak/say.js/blob/master/_autodocs/INDEX.md Shows how to speak text on Windows and retrieve a list of installed SAPI voices. ```javascript say.speak('Hello Windows', 'Microsoft Zira Desktop', 1.0) // List available voices say.getInstalledVoices((err, voices) => { console.log('Available:', voices) }) ``` -------------------------------- ### getInstalledVoices Source: https://github.com/marak/say.js/blob/master/_autodocs/api-reference/Say-class.md Retrieves a list of installed text-to-speech voices available on the system. This function is asynchronous and uses a Node-style callback to return the results. ```APIDOC ## getInstalledVoices(callback: function): void ### Description Retrieves a list of installed text-to-speech voices available on the system. This function is asynchronous and uses a Node-style callback to return the results. ### Method `getInstalledVoices` ### Parameters #### Callback - **callback** (function) - Required - Node-style callback with signature `function(err, voices)`. Called with `voices` as an array of strings representing available voice names. ### Callback Signature ```javascript function callback(err, voices) { // err: Error object if operation failed, null on success // voices: Array | null // On success: Array of voice names (strings) // On failure: null // Example: ['Alex', 'Samantha', 'Victoria', 'Fiona'] } ``` ### Throws/Rejects (via callback) - **Error**: Thrown if the platform does not support listing voices. - **Error**: Thrown if the underlying system process fails. ### Platform Support - **macOS (darwin)**: Not supported; throws an error. - **Linux**: Not supported; throws an error. - **Windows (win32)**: Full support. Returns installed SAPI voices. ### Usage Example ```javascript const say = require('say') // Get available voices on Windows if (process.platform === 'win32') { say.getInstalledVoices((err, voices) => { if (err) { return console.error('Failed to get voices:', err) } console.log('Available voices:', voices) // Example output: ['Microsoft Zira Desktop', 'Microsoft David Desktop'] // Use the first voice if (voices.length > 0) { say.speak('Hello', voices[0], 1.0) } }) } else { console.log('getInstalledVoices() only works on Windows') } ``` ``` -------------------------------- ### Windows PowerShell Speech Synthesis Example Source: https://github.com/marak/say.js/blob/master/_autodocs/ARCHITECTURE.md Illustrates using PowerShell and the System.Speech API to synthesize speech on Windows, including voice selection and rate adjustment. ```powershell Add-Type -AssemblyName System.speech $speak = New-Object System.Speech.Synthesis.SpeechSynthesizer $speak.SelectVoice('Microsoft Zira Desktop') $speak.Rate = 3 $speak.Speak([Console]::In.ReadToEnd()) ``` -------------------------------- ### Platform-Specific Voice Selection (macOS) Source: https://github.com/marak/say.js/blob/master/_autodocs/COMPLETION-REPORT.txt Example of selecting a specific voice on macOS. Voice names are platform-dependent. Use getInstalledVoices to find available voices. ```javascript const say = require('say'); // Example voice name for macOS, actual names may vary const macVoice = 'Macintosh'; say.speak('This is a macOS specific voice.', macVoice, 1.0, function(err) { if (err) { console.error('Error speaking on macOS:', err); } }); ``` -------------------------------- ### Say.js Platform Instantiation Source: https://github.com/marak/say.js/blob/master/_autodocs/api-reference/platform-implementations.md Demonstrates how to instantiate the Say factory class for different operating systems. Each instantiation returns a platform-specific implementation. ```javascript new Say('darwin') → SayPlatformDarwin new Say('linux') → SayPlatformLinux new Say('win32') → SayPlatformWin32 ``` -------------------------------- ### Generated PowerShell Code for Getting Voices Source: https://github.com/marak/say.js/blob/master/_autodocs/api-reference/platform-implementations.md Retrieves a list of installed SAPI voices on the Windows system using PowerShell. It loads the System.Speech assembly and iterates through the available voices to extract their names. ```powershell Add-Type -AssemblyName System.speech; $speak = New-Object System.Speech.Synthesis.SpeechSynthesizer; $speak.GetInstalledVoices() | % {$_.VoiceInfo.Name} ``` -------------------------------- ### Basic Say.js Usage Source: https://github.com/marak/say.js/blob/master/README.md Demonstrates how to import and use the say module to speak text. Automatically picks the platform or allows manual override. ```javascript // automatically pick platform const say = require('say') ``` ```javascript // or, override the platform const Say = require('say').Say const say = new Say('darwin' || 'win32' || 'linux') ``` ```javascript // Use default system voice and speed say.speak('Hello!') ``` ```javascript // Stop the text currently being spoken say.stop() ``` ```javascript // More complex example (with an OS X voice) and slow speed say.speak("What's up, dog?", 'Alex', 0.5) ``` ```javascript // Fire a callback once the text has completed being spoken say.speak("What's up, dog?", 'Good News', 1.0, (err) => { if (err) { return console.error(err) } console.log('Text has been spoken.') }); ``` ```javascript // Export spoken audio to a WAV file say.export("I'm sorry, Dave.", 'Cellos', 0.75, 'hal.wav', (err) => { if (err) { return console.error(err) } console.log('Text has been saved to hal.wav.') }) ``` -------------------------------- ### Instantiate Say Class Source: https://github.com/marak/say.js/blob/master/_autodocs/api-reference/Say-class.md Create a new Say instance. It can auto-detect the platform or you can specify it explicitly. ```javascript const Say = require('say').Say // Auto-detect platform const say = new Say() // Specify platform explicitly const say = new Say('darwin') // 'darwin', 'linux', or 'win32' ``` -------------------------------- ### Basic Say.js Usage Source: https://github.com/marak/say.js/blob/master/_autodocs/INDEX.md Demonstrates immediate speech, speech with a callback, and exporting audio to a file. The export function is only supported on macOS and Windows. ```javascript const say = require('say') // Speak immediately say.speak('Hello, World!') // With callback say.speak('Hello', 'Alex', 1.0, (err) => { if (err) console.error(err) else console.log('Done') }) // Export to file (macOS/Windows only) say.export('Hello', null, 1.0, 'output.wav', (err) => { if (err) console.error(err) }) ``` -------------------------------- ### Add New Platform Implementation (FreeBSD) Source: https://github.com/marak/say.js/blob/master/_autodocs/ARCHITECTURE.md This snippet shows how to create a new platform-specific implementation by extending the base platform class. It includes placeholders for building TTS commands, exporting, stopping, and enumerating voices. ```javascript const SayPlatformBase = require('./base.js') class SayPlatformFreeBSD extends SayPlatformBase { constructor() { super() this.baseSpeed = 100 } buildSpeakCommand({ text, voice, speed }) { // Implementation using FreeBSD TTS } buildExportCommand({ text, voice, speed, filename }) { // Export implementation } runStopCommand() { // Stop implementation } getVoices() { // Voice enumeration } } module.exports = SayPlatformFreeBSD ``` -------------------------------- ### Basic Speech Output Source: https://github.com/marak/say.js/blob/master/_autodocs/INDEX.md Demonstrates how to use the `speak` method for simple text-to-speech output. Requires the 'say' module to be imported. ```javascript const say = require('say') say.speak('Hello world') ``` -------------------------------- ### macOS Specific Speech Source: https://github.com/marak/say.js/blob/master/_autodocs/INDEX.md Example of speaking text with a specific voice and speed on macOS. ```javascript say.speak('Hello macOS', 'Victoria', 0.5) ``` -------------------------------- ### Factory Pattern Source: https://github.com/marak/say.js/blob/master/_autodocs/COMPLETION-REPORT.txt Details on how to create instances of the Say class using factory and singleton patterns. ```APIDOC ## Factory and Singleton Patterns Say.js supports creating instances of the `Say` class using a factory pattern, including a singleton implementation. ### `new Say(platform)` This is the constructor for the `Say` class. You can optionally specify the platform to use. - **platform** (string) - Optional - The desired platform ('darwin', 'linux', 'win32'). If not provided, the system will attempt to auto-detect the platform. ### Singleton Pattern Say.js may internally manage a singleton instance, ensuring that only one instance of the `Say` class is active for a given platform context, simplifying resource management. ``` -------------------------------- ### Say.getInstalledVoices Source: https://github.com/marak/say.js/blob/master/_autodocs/types.md Retrieves a list of all installed voices available on the system. This is useful for selecting specific voices for speech synthesis. ```APIDOC ## Say.getInstalledVoices ### Description Retrieves a list of all installed voices available on the system. This is useful for selecting specific voices for speech synthesis. ### Method GET ### Endpoint `/say/voices` (This is a conceptual representation as the library is SDK-based, not HTTP) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **callback** (errorCallback) - Required - A callback function that will receive an error (if any) and an array of installed voice names (strings). ### Request Example ```javascript const say = require('say') say.getInstalledVoices((err, voices) => { if (err) { console.error('Error getting installed voices:', err) } else { console.log('Installed voices:', voices) } }) ``` ### Response #### Success Response (200) - **voices** (Array) - An array of strings, where each string is the name of an installed voice. #### Response Example ```json { "voices": ["Alex", "Samantha", "Daniel", "Karen"] } ``` ``` -------------------------------- ### Using the Default Singleton Instance Source: https://github.com/marak/say.js/blob/master/_autodocs/api-reference/Say-class.md Access the pre-instantiated singleton instance to use the auto-detected platform for speech synthesis. No explicit instantiation is required. ```javascript const say = require('say') // This is already a Say instance with auto-detected platform say.speak('Using the default singleton') ``` -------------------------------- ### Say.js Architectural Pattern: Platform Adapter Source: https://github.com/marak/say.js/blob/master/_autodocs/ARCHITECTURE.md Illustrates the platform adapter pattern used in say.js. The Say class acts as a factory, delegating to platform-specific implementations (Darwin, Linux, Win32) which inherit from a SayPlatformBase abstract class. ```text User Code ↓ ┌─────────────┐ │ Say Class │ (Factory) │ (index.js) │ └──────┬──────┘ ├─→ Say Platform Darwin (macOS) ├─→ Say Platform Linux └─→ Say Platform Win32 All inherit from ↓ SayPlatformBase (Abstract Base Class) ├── speak() ├── export() ├── stop() ├── getInstalledVoices() └── convertSpeed() ``` -------------------------------- ### Module Exports and Usage (CommonJS) Source: https://github.com/marak/say.js/blob/master/_autodocs/types.md Illustrates how to import and use the say.js module in a CommonJS environment. It shows importing the default singleton, the Say constructor class, and platform constants. ```javascript // CommonJS const say = require('say') const { Say, platforms } = require('say') // Using singleton say.speak('Using singleton', 'Alex', 1.0) // Using class const macSay = new Say(platforms.MACOS) ``` -------------------------------- ### Conditional Speech Synthesis Source: https://github.com/marak/say.js/blob/master/_autodocs/COMPLETION-REPORT.txt Example of conditionally speaking text based on a condition. This pattern is useful for controlling speech output dynamically. ```javascript const say = require('say'); const shouldSpeak = true; if (shouldSpeak) { say.speak('This message is spoken conditionally.', null, 1.0, (err) => { if (err) { console.error('Conditional speak error:', err); } }); } else { console.log('Speech was skipped due to condition.'); } ``` -------------------------------- ### Platform Detection Wrapper Source: https://github.com/marak/say.js/blob/master/_autodocs/GETTING-STARTED.md Create a wrapper class that detects the platform and provides platform-specific methods for speaking and exporting audio. Includes error handling for unsupported operations. ```javascript const { Say, platforms } = require('say') class SafeSpeaker { constructor() { this.say = new Say() this.platform = process.platform } canExport() { return this.platform !== 'linux' } speak(text, voice, speed, callback) { if (!text || typeof text !== 'string') { return callback(new Error('Text must be a non-empty string')) } this.say.speak(text, voice, speed, callback) } export(text, voice, speed, filename, callback) { if (!this.canExport()) { return callback(new Error('Export not supported on Linux')) } this.say.export(text, voice, speed, filename, callback) } } // Usage const speaker = new SafeSpeaker() speaker.speak('Hello', null, 1.0, (err) => { if (err) console.error(err) }) if (speaker.canExport()) { speaker.export('Test', null, 1.0, 'output.wav', (err) => { if (err) console.error(err) }) } ``` -------------------------------- ### Handle Voice Process Exit Error Source: https://github.com/marak/say.js/blob/master/_autodocs/errors.md This snippet demonstrates how to catch errors that occur if the underlying process for querying installed voices fails. ```javascript const say = require('say') say.getInstalledVoices((err, voices) => { if (err) { console.error(err.message) // Example Output: "say.getInstalledVoices(): could not get installed voices, had an error [code: 1] [signal: null]" } }) ``` -------------------------------- ### Conditional Platform Features (Linux vs. Others) Source: https://github.com/marak/say.js/blob/master/_autodocs/GETTING-STARTED.md This snippet shows how to handle platform-specific features, like exporting audio to a file on non-Linux systems and speaking directly on Linux. It uses the Say class and checks the process platform. ```javascript const { Say, platforms } = require('say') const say = new Say() async function smartExport(text, voice, filename) { if (process.platform === 'linux') { console.log('Export not available on Linux. Using speech instead.') return new Promise((resolve, reject) => { say.speak(text, voice, 1.0, (err) => { if (err) reject(err) else resolve() }) }) } else { return new Promise((resolve, reject) => { say.export(text, voice, 1.0, filename, (err) => { if (err) reject(err) else resolve() }) }) } } smartExport('Hello', null, 'output.wav') ``` -------------------------------- ### Build Export Command Arguments Source: https://github.com/marak/say.js/blob/master/_autodocs/api-reference/platform-implementations.md Internal method to construct command-line arguments for exporting audio to a WAV file using the 'say' command. Requires filename and other speech options. ```javascript buildExportCommand({ text, voice, speed, filename }) ``` -------------------------------- ### Creating a Custom Say Instance Source: https://github.com/marak/say.js/blob/master/_autodocs/api-reference/Say-class.md Instantiate the Say class directly to create a new speech synthesis instance with an explicitly defined platform. This is useful for environments where the default platform detection might not be suitable or when specific platform behavior is needed. ```javascript const { Say } = require('say') // Create a new instance with explicit platform const customSay = new Say('darwin') ``` -------------------------------- ### TypeScript Usage of Say Class Source: https://github.com/marak/say.js/blob/master/_autodocs/types.md Demonstrates creating and using instances of the Say class in TypeScript. It shows how to use the default singleton instance and how to create new instances with specific platforms, including type-safe callbacks. ```typescript import say from 'say' import { Say } from 'say' // Using the default singleton (auto-detected platform) say.speak('Hello', 'Alex', 1.0, (err) => { if (err) console.error(err) }) // Creating a new instance with explicit platform const customSay: Say = new Say('darwin') customSay.speak('macOS only', null, 1.0, (err) => { if (err) console.error(err) }) // Type-safe callback const callback: ((err?: Error | null) => void) = (err) => { if (err) console.error('Error:', err.message) } customSay.speak('Typed', 'Samantha', 0.5, callback) ``` -------------------------------- ### Declare Say Class Source: https://github.com/marak/say.js/blob/master/_autodocs/INDEX.md Declares the Say class with its constructor and methods for speech synthesis. Supports basic speech, exporting to files, stopping speech, and retrieving installed voices. ```typescript declare class Say { constructor(platform?: string) speak( text: string, voice?: string, speed?: number, callback?: errorCallback ): void export( text: string, voice?: string, speed?: number, filePath: string, callback?: errorCallback ): void stop(callback?: errorCallback): void getInstalledVoices(callback: errorCallback): void } ``` -------------------------------- ### Say Class Methods Source: https://github.com/marak/say.js/blob/master/_autodocs/COMPLETION-REPORT.txt The Say class provides the core functionality for text-to-speech. It includes methods for speaking text, exporting audio, stopping speech, and retrieving installed voices. ```APIDOC ## Say Class API Reference This section details the methods available on the `Say` class. ### Constructor Creates a new instance of the `Say` class. - **platform** (string) - Optional - The platform to use for text-to-speech (e.g., 'darwin', 'linux', 'win32'). Defaults to the auto-detected platform. ### `speak(text, options, callback)` Converts the given text into speech and plays it. - **text** (string) - Required - The text to be spoken. - **options** (object) - Optional - Configuration options for speech. - **speed** (number) - Optional - The speaking rate (e.g., 0.5 for half speed, 1 for normal speed). - **callback** (function) - Optional - A function to be called when speech is finished or an error occurs. #### Example ```javascript const say = require('say'); say.speak('Hello, world!', null, (err) => { if (err) { console.error('Error speaking:', err); } }); ``` ### `export(text, filename, callback)` Converts the given text into speech and saves it to an audio file. - **text** (string) - Required - The text to be spoken. - **filename** (string) - Required - The path to the output audio file. - **callback** (function) - Optional - A function to be called upon completion or error. #### Example ```javascript const say = require('say'); say.export('This will be saved to a file.', 'output.wav', (err) => { if (err) { console.error('Error exporting audio:', err); } }); ``` ### `stop()` Stops the current speech playback. ### `getInstalledVoices(callback)` Retrieves a list of installed voices available on the system. - **callback** (function) - Required - A function that will be called with the list of voices or an error. - **voices** (array) - A list of available voice objects. - **err** (Error) - An error object if an error occurred. #### Example ```javascript const say = require('say'); say.getInstalledVoices((err, voices) => { if (err) { console.error('Error getting voices:', err); return; } console.log('Installed voices:', voices); }); ``` ``` -------------------------------- ### Update Factory for New Platform Source: https://github.com/marak/say.js/blob/master/_autodocs/ARCHITECTURE.md This snippet demonstrates how to update the main factory class to recognize and instantiate the new platform. It shows the conditional logic for selecting the appropriate platform implementation based on `process.platform`. ```javascript const SayFreeBSD = require('./platform/freebsd.js') class Say { constructor(platform) { if (!platform) platform = process.platform if (platform === MACOS) return new SayMacos() else if (platform === LINUX) return new SayLinux() else if (platform === WIN32) return new SayWin32() else if (platform === 'freebsd') return new SayFreeBSD() // ← Add this throw new Error(...) } } ``` -------------------------------- ### Basic Say.js speak usage Source: https://github.com/marak/say.js/blob/master/_autodocs/api-reference/Say-class.md Demonstrates the simplest way to use the `speak` method to say a string of text without specifying voice, speed, or a callback. ```javascript const say = require('say') // Basic usage without callback say.speak('Hello world') ``` -------------------------------- ### Limitation: Rapid Speak Calls Source: https://github.com/marak/say.js/blob/master/_autodocs/ARCHITECTURE.md This example illustrates a known limitation where rapid calls to speak() can lead to the loss of references to earlier child processes, preventing independent stopping. ```javascript say.speak('Message 1') say.speak('Message 2') // ← this.child now points to Message 2 // Message 1 reference is lost; can't stop it independently ``` -------------------------------- ### Instantiate Say with API Engine Source: https://github.com/marak/say.js/wiki/Proposed-1.0-API Creates a new Say instance configured to use the 'api' engine. This is for utilizing external speech synthesis services. ```javascript var online = new Say({ engine: 'api' }); ``` -------------------------------- ### Say Constructor Source: https://github.com/marak/say.js/blob/master/_autodocs/api-reference/Say-class.md Creates a new Say instance. It can automatically detect the platform or use a specified one for text-to-speech operations. ```APIDOC ## Say Constructor ### Description Creates a new Say instance that automatically detects or uses the specified platform for text-to-speech operations. ### Signature `Say(platform?: string)` ### Parameters #### Path Parameters - **platform** (string) - Optional - The platform to use. Valid values: `'darwin'` (macOS), `'linux'`, `'win32'` (Windows). If not provided, `process.platform` is used automatically. ### Throws - **Error** — When an unsupported platform string is provided. Error message: `"new Say(): unsupported platorm! {platform}"` ### Usage Example ```javascript const { Say } = require('say') // Use auto-detected platform const say = new Say() say.speak('Hello world') // Override platform for testing try { const winSay = new Say('win32') } catch (err) { console.error('Unsupported platform:', err.message) } ``` ``` -------------------------------- ### Handle Unsupported Platform Error Source: https://github.com/marak/say.js/blob/master/_autodocs/errors.md Instantiating Say with an invalid platform string throws an error. Ensure the platform is one of 'darwin', 'linux', or 'win32'. ```javascript const { Say } = require('say') try { const say = new Say('bsd') // Unsupported platform } catch (err) { console.error(err.message) // Output: "new Say(): unsupported platorm! bsd" } ``` ```javascript const { Say, platforms } = require('say') const validPlatforms = ['darwin', 'linux', 'win32'] const platform = process.argv[2] || process.platform if (!validPlatforms.includes(platform)) { console.error(`Unsupported platform: ${platform}`) process.exit(1) } const say = new Say(platform) ``` -------------------------------- ### Say Class Interface Definition Source: https://github.com/marak/say.js/blob/master/_autodocs/types.md TypeScript interface for the Say class, outlining its methods for text-to-speech operations. This includes methods for speaking, exporting audio, stopping playback, and retrieving installed voices. ```typescript declare class Say { public export(text: string, voice?: string, speed?: number, filePath?: string, callback?: errorCallback): void public speak(text: string, voice?: string, speed?: number, callback?: errorCallback): void public stop(): void public getInstalledVoices(callback: errorCallback): void } ``` -------------------------------- ### Speak with Default Settings Source: https://github.com/marak/say.js/blob/master/_autodocs/GETTING-STARTED.md Use the simplest method to speak text with the default voice and speed. Requires the 'say' module. ```javascript const say = require('say') // Speak immediately with default voice and speed say.speak('Hello, World!') ``` -------------------------------- ### Promisifying the Say.speak Method Source: https://github.com/marak/say.js/blob/master/_autodocs/ARCHITECTURE.md Demonstrates how to wrap the Say.js speak method with Node.js's promisify utility to enable the use of async/await syntax. ```javascript const { promisify } = require('util') const speak = promisify((text, voice, speed, cb) => { say.speak(text, voice, speed, cb) }) await speak('Hello', null, 1.0) ``` -------------------------------- ### Say.js speak with voice and speed Source: https://github.com/marak/say.js/blob/master/_autodocs/api-reference/Say-class.md Shows how to use the `speak` method with custom voice and speed parameters. Note that speed is not supported on Windows. ```javascript // With voice and speed say.speak("What's up, dog?", 'Alex', 0.5) ``` -------------------------------- ### Speak Messages Sequentially with Callbacks Source: https://github.com/marak/say.js/blob/master/_autodocs/GETTING-STARTED.md Use this pattern to speak a series of messages one after another using callbacks. Ensure the 'say' module is imported. ```javascript const say = require('say') function speakSequence(messages) { let index = 0 function next() { if (index >= messages.length) { console.log('All messages spoken') return } const msg = messages[index++] say.speak(msg, null, 1.0, (err) => { if (err) console.error(err) else next() }) } next() } // Usage speakSequence([ 'First message', 'Second message', 'Third message' ]) ``` -------------------------------- ### Handle Platform Not Supported Error for getInstalledVoices Source: https://github.com/marak/say.js/blob/master/_autodocs/errors.md Shows how to detect and handle the error when getInstalledVoices() is called on an unsupported platform like macOS or Linux. ```javascript const say = require('say') if (process.platform === 'darwin') { say.getInstalledVoices((err) => { if (err) { console.error(err.message) // Output: "say.export(): does not support platform darwin" } }) } ``` ```javascript const say = require('say') if (process.platform === 'win32') { say.getInstalledVoices((err, voices) => { if (err) { console.error('Failed to get voices:', err) return } console.log('Available voices:', voices) }) } else { console.log('Voice enumeration not available on this platform') // Use hardcoded defaults for other platforms } ``` -------------------------------- ### Handling Export Not Supported on Linux Platform Source: https://github.com/marak/say.js/blob/master/_autodocs/errors.md Demonstrates how to check the current platform and use an alternative method (speak()) if export is not supported, such as on Linux. ```javascript const { Say, platforms } = require('say') const say = new Say() if (process.platform === 'linux') { console.log('Export not available on this platform') // Use alternative approach like speak() say.speak('Hello', null, 1.0) } else { say.export('Hello', null, 1.0, 'output.wav', (err) => { if (err) console.error(err) }) } ``` -------------------------------- ### macOS Export Command Construction Source: https://github.com/marak/say.js/blob/master/_autodocs/MODULE-GRAPH.md Constructs the command-line arguments for exporting audio to a WAV file using the 'say' command on macOS. Specifies data format and sample rate. ```javascript buildExportCommand() { const { voice, speed } = this.options; const rate = Math.ceil(this.baseSpeed * speed); return `say -v ${voice} -r ${rate} --data-format=LEF32@32000 -o "${this.file}" "${this.text}"`; } ``` -------------------------------- ### Platform Implementations Source: https://github.com/marak/say.js/blob/master/_autodocs/COMPLETION-REPORT.txt Details on the base class and specific implementations for different operating systems. ```APIDOC ## Platform Implementations Say.js provides an abstract base class and concrete implementations for various operating systems. ### `SayPlatformBase` (abstract) The abstract base class that defines the interface for all platform-specific implementations. It outlines methods for speech synthesis and management. ### `SayPlatformDarwin` (macOS) Implementation of `SayPlatformBase` for macOS, utilizing system speech synthesis capabilities. ### `SayPlatformLinux` (Linux) Implementation of `SayPlatformBase` for Linux, typically using external command-line tools like `espeak` or `festival`. ### `SayPlatformWin32` (Windows) Implementation of `SayPlatformBase` for Windows, leveraging the built-in Windows Speech API. ```