import { WebSocket } from "ws";
import { createReadStream } from "fs";
const WS_URL = "wss://platform.modulate.ai/api/velma-2-music-detection-streaming";
const API_KEY = "YOUR_API_KEY";
async function streamAudio(filePath, audioFormat) {
const url = `${WS_URL}?api_key=${API_KEY}&audio_format=${audioFormat}`;
const ws = new WebSocket(url);
await new Promise((resolve, reject) => {
ws.on("open", () => {
const stream = createReadStream(filePath, { highWaterMark: 65536 });
stream.on("data", (chunk) => ws.send(chunk));
stream.on("end", () => ws.send(""));
stream.on("error", reject);
});
ws.on("message", (data) => {
const msg = JSON.parse(data);
if (msg.type === "frame") {
const { start_time_ms, end_time_ms, music_prob, speech_prob } = msg.frame;
console.log(
`${start_time_ms}ms – ${end_time_ms}ms ` +
`music=${music_prob.toFixed(4)} speech=${speech_prob.toFixed(4)}`
);
} else if (msg.type === "done") {
console.log(`\nDone — ${msg.duration_ms}ms, ${msg.frame_count} frames`);
console.log(`music=${msg.music_pct}% speech=${msg.speech_pct}% label=${msg.primary_label}`);
ws.close();
resolve();
} else if (msg.type === "error") {
reject(new Error(`Server error: ${msg.error}`));
}
});
ws.on("error", reject);
});
}
await streamAudio("/path/to/audio.mp3", "mp3");