/** * Fish Audio Unlimited TTS & Voice Model Scraper * Engine: Fish Audio S2.1 Pro Free Tier (Unlimited 0 Credit) & Public Voice Models * Author: Vamz Spectre / VamxAPI * * Download: * curl -sL "https://code.vamxapi.my.id/snippet/raw/fish-audio" -o fish-audio.js * * Usage CLI: * # Search Voice Models * node fish-audio.js search "indonesia" * * # Generate TTS (Free Tier s2.1-pro-free) * node fish-audio.js tts "Halo semuanya! Selamat datang di VamxAPI." [reference_id] [api_key] * * # Quick TTS (Auto default voice) * node fish-audio.js "Halo kawan, ini adalah suara AI Fish Audio tanpa batas kuota." */ const https = require("https"); const http = require("http"); const fs = require("fs"); const path = require("path"); const FISH_API_BASE = "https://api.fish.audio"; /** * HTTP Request Helper with Promise */ function request(url, options = {}, postData = null) { return new Promise((resolve, reject) => { const parsedUrl = new URL(url); const client = parsedUrl.protocol === "https:" ? https : http; const req = client.request( url, { method: options.method || "GET", headers: options.headers || {}, timeout: options.timeout || 30000, }, (res) => { const isStream = options.responseType === "stream"; if (isStream) { return resolve(res); } const chunks = []; res.on("data", (chunk) => chunks.push(chunk)); res.on("end", () => { const buffer = Buffer.concat(chunks); const contentType = res.headers["content-type"] || ""; if (res.statusCode >= 400) { let errorBody = buffer.toString("utf-8"); try { errorBody = JSON.parse(errorBody); } catch (e) {} return reject({ statusCode: res.statusCode, headers: res.headers, error: errorBody, }); } if (contentType.includes("application/json")) { try { return resolve({ statusCode: res.statusCode, headers: res.headers, data: JSON.parse(buffer.toString("utf-8")), }); } catch (e) { return resolve({ statusCode: res.statusCode, headers: res.headers, data: buffer.toString("utf-8"), }); } } resolve({ statusCode: res.statusCode, headers: res.headers, buffer: buffer, }); }); } ); req.on("error", (err) => reject(err)); req.on("timeout", () => { req.destroy(); reject(new Error("Request timeout")); }); if (postData) { if (typeof postData === "string" || Buffer.isBuffer(postData)) { req.write(postData); } else { req.write(JSON.stringify(postData)); } } req.end(); }); } /** * 1. Search Public Voice Models (100% Free & No Auth Required) * @param {string} query Search keyword (e.g. "indonesia", "anime", "narrator") * @param {number} pageSize Number of results (default 10) */ async function searchVoices(query = "", pageSize = 10) { const url = `${FISH_API_BASE}/model?title=${encodeURIComponent(query)}&page_size=${pageSize}&sort_by=score`; const res = await request(url, { headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", Accept: "application/json", }, }); const items = (res.data?.items || []).map((item) => ({ id: item._id, title: item.title, description: item.description || "", languages: item.languages || [], tags: item.tags || [], sample_audio: item.samples?.[0]?.audio || null, creator: item.author?.username || "Community", })); return { total: res.data?.total || items.length, count: items.length, voices: items, }; } /** * 2. Get Voice Model Detail * @param {string} modelId Fish Audio Model ID */ async function getVoiceDetail(modelId) { const url = `${FISH_API_BASE}/model/${modelId}`; const res = await request(url, { headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", Accept: "application/json", }, }); const data = res.data; return { id: data._id, title: data.title, description: data.description, languages: data.languages, samples: (data.samples || []).map((s) => ({ title: s.title, audio_url: s.audio, })), }; } /** * 3. Generate Speech with Fish Audio Drama-3 (Zero-Shot AI Generation) * @param {Object} options * @param {string} options.text Text to synthesize * @param {string} [options.voiceId="clone1"] Voice preset ('clone1' | 'clone2' | 'clone3') * @param {string} [options.hfToken=""] Optional HuggingFace token for ZeroGPU quota */ async function textToSpeechDrama3(options = {}) { const { text, voiceId = "clone1", hfToken = process.env.HF_TOKEN || "", outputPath = null, } = options; if (!text) { throw new Error("Parameter 'text' wajib diisi."); } const payload = { text: text, voice: { mode: "clone", id: voiceId, }, }; const headers = { "Content-Type": "application/json", "User-Agent": "Mozilla/5.0", }; if (hfToken) { headers["Authorization"] = `Bearer ${hfToken}`; } const startTime = Date.now(); const res = await request( "https://fishaudio-drama-3.hf.space/api/generate", { method: "POST", headers: headers, responseType: "stream", }, payload ); return new Promise((resolve, reject) => { let pcmChunks = []; let sampleRate = 44100; let takeId = null; let errorMsg = null; res.on("data", (chunk) => { const lines = chunk.toString("utf-8").split("\n"); for (const line of lines) { const trimmed = line.trim(); if (trimmed.startsWith("data: ")) { try { const ev = JSON.parse(trimmed.slice(6)); if (ev.type === "start") { takeId = ev.take_id; sampleRate = ev.sample_rate || 44100; } else if (ev.type === "audio") { pcmChunks.push(Buffer.from(ev.pcm, "base64")); } else if (ev.type === "error") { errorMsg = ev.message; } } catch (e) {} } } }); res.on("end", () => { if (errorMsg) { return resolve({ success: false, model: "drama-3", message: errorMsg, help: "Tambahkan HF token (export HF_TOKEN=hf_...) jika ZeroGPU IP limit tercapai.", }); } const pcmBuffer = Buffer.concat(pcmChunks); if (pcmBuffer.length === 0) { return resolve({ success: false, model: "drama-3", message: "No audio generated or ZeroGPU limit reached.", }); } // Convert PCM 16-bit 44.1kHz to WAV buffer const wavHeader = Buffer.alloc(44); const totalDataLen = pcmBuffer.length; const totalFileLen = totalDataLen + 36; wavHeader.write("RIFF", 0); wavHeader.writeUInt32LE(totalFileLen, 4); wavHeader.write("WAVE", 8); wavHeader.write("fmt ", 12); wavHeader.writeUInt32LE(16, 16); wavHeader.writeUInt16LE(1, 20); // PCM wavHeader.writeUInt16LE(1, 22); // Mono wavHeader.writeUInt32LE(sampleRate, 24); wavHeader.writeUInt32LE(sampleRate * 2, 28); // byte rate wavHeader.writeUInt16LE(2, 32); // block align wavHeader.writeUInt16LE(16, 34); // bits per sample wavHeader.write("data", 36); wavHeader.writeUInt32LE(totalDataLen, 40); const wavBuffer = Buffer.concat([wavHeader, pcmBuffer]); const savedPath = outputPath || path.join("/tmp", `drama3_${Date.now()}.wav`); fs.writeFileSync(savedPath, wavBuffer); resolve({ success: true, model: "drama-3", take_id: takeId, text: text, sample_rate: sampleRate, audio_size_bytes: wavBuffer.length, file_path: savedPath, base64_audio: `data:audio/wav;base64,${wavBuffer.toString("base64")}`, latency_ms: Date.now() - startTime, }); }); res.on("error", (err) => reject(err)); }); } /** * 4. Generate Speech with Fish Audio S2.1 Pro Free Tier (Unlimited 0 Credit) * @param {Object} options * @param {string} options.text Text to synthesize * @param {string} [options.reference_id] Voice model ID * @param {string} [options.apiKey] Fish Audio API Key (Free tier key from fish.audio/app/api-keys) * @param {string} [options.format="mp3"] Audio format ('mp3' | 'wav' | 'pcm') * @param {number} [options.speed=1.0] Speech speed * @param {number} [options.volume=0] Volume boost * @param {string} [options.outputPath] Optional local file path to save audio */ async function textToSpeech(options = {}) { const { text, reference_id = "8a62f569b9e54dda88dad8560635a4ad", // Default: Wanita Indonesia apiKey = process.env.FISH_AUDIO_KEY || "", format = "mp3", speed = 1.0, volume = 0, outputPath = null, } = options; if (!text || typeof text !== "string") { throw new Error("Parameter 'text' wajib diisi."); } // Model s2.1-pro-free provides UNLIMITED $0 free tier access const payload = { text: text, format: format, reference_id: reference_id || undefined, chunk_length: 300, normalize: true, latency: "normal", prosody: { speed: Number(speed) || 1.0, volume: Number(volume) || 0, normalize_loudness: true, }, }; const headers = { "Content-Type": "application/json", model: "s2.1-pro-free", // <--- THE UNLIMITED FREE TIER MODEL "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)", }; if (apiKey) { headers["Authorization"] = apiKey.startsWith("Bearer ") ? apiKey : `Bearer ${apiKey}`; } const startTime = Date.now(); try { const res = await request( `${FISH_API_BASE}/v1/tts`, { method: "POST", headers: headers, }, payload ); const durationMs = Date.now() - startTime; const audioBuffer = res.buffer; let savedPath = outputPath; if (!savedPath) { const fileName = `fish_audio_${Date.now()}.${format}`; savedPath = path.join("/tmp", fileName); } fs.writeFileSync(savedPath, audioBuffer); return { success: true, model: "s2.1-pro-free", tier: "UNLIMITED_FREE_TIER", reference_id: reference_id, text: text, format: format, audio_size_bytes: audioBuffer.length, file_path: savedPath, base64_audio: `data:audio/${format};base64,${audioBuffer.toString("base64")}`, latency_ms: durationMs, }; } catch (err) { // If missing API key, provide helpful guidance with instant link if (err.statusCode === 401) { return { success: false, status: 401, model: "s2.1-pro-free", tier: "UNLIMITED_FREE_TIER", message: "Memerlukan API Key gratis dari Fish Audio untuk mengaktifkan model unli 's2.1-pro-free'.", how_to_get_key: [ "1. Buka https://fish.audio/app/api-keys", "2. Klik 'Create Key' (100% Gratis & Instan tanpa kartu kredit)", "3. Jalankan CLI: node fish-audio.js tts 'teks kamu' [voice_id] [api_key]", " atau set export FISH_AUDIO_KEY='your_key_here'", ], public_models_available: "Jalankan 'node fish-audio.js search ' untuk mencari ribuan suara gratis tanpa login.", }; } throw err; } } // ========================================== // CLI RUNNER (Real-time Execution) // ========================================== async function main() { const args = process.argv.slice(2); const command = args[0] || "search"; try { if (command === "search" || command === "find") { const query = args[1] || "indonesia"; const limit = parseInt(args[2], 10) || 5; const result = await searchVoices(query, limit); console.log(JSON.stringify(result, null, 2)); } else if (command === "detail") { const modelId = args[1] || "8a62f569b9e54dda88dad8560635a4ad"; const result = await getVoiceDetail(modelId); console.log(JSON.stringify(result, null, 2)); } else if (command === "drama3" || command === "drama") { const text = args[1] || "Halo kawan, ini adalah tes Fish Audio Drama-3."; const voiceId = args[2] || "clone1"; const hfToken = args[3] || process.env.HF_TOKEN || ""; const result = await textToSpeechDrama3({ text: text, voiceId: voiceId, hfToken: hfToken, }); console.log(JSON.stringify(result, null, 2)); } else if (command === "tts") { const text = args[1] || "Halo kawan, ini adalah uji coba Fish Audio Text To Speech."; const refId = args[2] || "8a62f569b9e54dda88dad8560635a4ad"; const key = args[3] || process.env.FISH_AUDIO_KEY || ""; const result = await textToSpeech({ text: text, reference_id: refId, apiKey: key, }); console.log(JSON.stringify(result, null, 2)); } else { // Default: if argument is a sentence, treat as TTS const text = args.join(" "); const result = await textToSpeech({ text: text }); console.log(JSON.stringify(result, null, 2)); } } catch (error) { console.error( JSON.stringify( { success: false, error: error.message || error, }, null, 2 ) ); process.exit(1); } } if (require.main === module) { main(); } module.exports = { searchVoices, getVoiceDetail, textToSpeech, textToSpeechDrama3, };