Moknah 문서
무료로 시작하기
API 레퍼런스

실시간 음성 텍스트 변환 (STT)

WebSocket을 사용하여 실시간 스트리밍 오디오를 텍스트로 전사합니다

WSS wss://moknah.io/api/v1/stt/ws/

원시 오디오를 서버로 스트리밍하고 양방향 실시간 전사를 받아보세요. 서버는 부분 결과(사용자가 말할 때의 실시간 텍스트)와 최종 결과(단어 단위 타임스탬프가 포함된 완성된 문장)로 응답합니다.

💳 선불 요금 미터기 (분당 400 크레딧)

스트리밍은 실시간으로 이루어져 예측할 수 없으므로 선불 미터기를 사용합니다. 연결 시 처음 60초에 해당하는 400 크레딧이 즉시 예약됩니다. 연결이 종료되면 초 단위로 정확한 사용량을 계산하여 사용하지 않은 크레딧을 계정으로 자동 환불해 드립니다!

인증 및 연결

WebSocket 연결을 인증해야 합니다. 인증 방법은 클라이언트 환경에 따라 다릅니다:

  • 프런트엔드 브라우저: 표준 브라우저 WebSocket은 사용자 지정 HTTP 헤더를 지원하지 않습니다. API 키를 쿼리 매개변수(?api_key=YOUR_KEY)로 포함해야 합니다.
  • 백엔드 / Python / Node.js: 표준 HTTP 헤더인 Authorization: Bearer YOUR_API_KEY를 사용할 수 있습니다.
쿼리 매개변수 필수 유형 설명
api_key 조건부 string Moknah API 키입니다. (Authorization 헤더를 통해 전달되지 않은 경우 여기에 필수 입력).
language 선택 사항 string 전사할 언어 코드입니다. 기본값은 ar-JO입니다. 지원되는 코드에는 ar-SA, ar-EG, en-US 등이 있습니다.

오디오 사양

⚠️ 중요: 원시 바이너리(Raw Binary) 전용

압축된 오디오 파일(.mp3, .m4a 등)이나 헤더가 포함된 표준 .wav 파일을 WebSocket으로 전송하지 마세요. AI가 무작위 노이즈나 빈 문자열을 출력하게 됩니다. WebSocket은 오직 원시 바이너리 PCM 프레임만 허용합니다.

소켓을 통해 바이너리 프레임을 전송하기 전에 오디오 스트림이 다음 사양과 정확히 일치하는지 확인하세요:

  • 샘플 레이트: 16,000 Hz (16 kHz)
  • 비트 심도: 16비트 정수 (Int16)
  • 채널: 1 (모노)
  • 청크 크기: 작은 청크 단위로 전송하세요(예: 100ms / 3200바이트). 256KB보다 큰 청크는 거부됩니다.

서버 응답 (JSON 이벤트)

서버로 바이너리 오디오를 스트리밍하면 서버는 JSON 텍스트 프레임으로 비동기 응답을 보냅니다.

이벤트 유형 페이로드 예시
연결 성공
인증이 성공하면 즉시 전송됩니다.
{"status": "connected", "message": "오디오 스트리밍 준비 완료..."}
부분 결과
지속적으로 전송됩니다. 실시간 타이핑 자막을 렌더링하는 데 사용됩니다.
{"type": "partial", "text": "مرحبا بك في منصة"}
최종 결과
문장이 완성되면 전송됩니다. 타임스탬프가 포함됩니다.
{
  "type": "final",
  "text": "مرحبا بك في منصة مكنة.",
  "words": [
    {"word": "مرحبا", "start_time_ms": 150, "duration_ms": 300},
    {"word": "بك", "start_time_ms": 460, "duration_ms": 200}
  ]
}

스트림 종료: When the user stops speaking, send a JSON text frame: {"command": "stop"} to safely close the connection and calculate the final refund.


연동 예제

# pip install websockets pyaudio
import asyncio
import websockets
import json
import pyaudio
import sys

API_KEY = "YOUR_API_KEY"
URL = "wss://moknah.io/api/v1/stt/ws/?language=ar-SA"

# 16kHz, 16-bit, Mono (100ms chunks)
CHUNK = 1600

async def stream_live_microphone(ws):
    audio = pyaudio.PyAudio()
    stream = audio.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, frames_per_buffer=CHUNK)

    print("🎤 Microphone is LIVE. Start speaking!")
    loop = asyncio.get_running_loop()

    try:
        while True:
            data = await loop.run_in_executor(None, stream.read, CHUNK, False)
            await ws.send(data)
            await asyncio.sleep(0.001)
    except asyncio.CancelledError:
        await ws.send(json.dumps({"command": "stop"}))
    finally:
        stream.stop_stream()
        stream.close()
        audio.terminate()

async def receive_transcriptions(ws):
    async for message in ws:
        data = json.loads(message)
        if data.get('type') == 'partial':
            sys.stdout.write(f"\r⏳ {data['text']}")
            sys.stdout.flush()
        elif data.get('type') == 'final':
            sys.stdout.write(f"\r✅ {data['text']}\n")
            sys.stdout.flush()

async def main():
    headers = {"Authorization": f"Bearer {API_KEY}"}
    async with websockets.connect(URL, additional_headers=headers) as ws:
        await asyncio.gather(
            asyncio.create_task(stream_live_microphone(ws)),
            asyncio.create_task(receive_transcriptions(ws))
        )

asyncio.run(main())
// 1. Connect to WebSocket
const ws = new WebSocket('wss://moknah.io/api/v1/stt/ws/?api_key=YOUR_API_KEY&language=ar-SA');

ws.onmessage = (event) => {
    const data = JSON.parse(event.data);
    if (data.type === 'partial') {
        console.log("Live:", data.text);
    } else if (data.type === 'final') {
        console.log("Final:", data.text);
    }
};

// 2. Capture Microphone Audio on Connection
ws.onopen = async () => {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });

    // Force 16kHz sample rate for the AudioContext
    const audioCtx = new AudioContext({ sampleRate: 16000 });
    const source = audioCtx.createMediaStreamSource(stream);
    const processor = audioCtx.createScriptProcessor(4096, 1, 1);

    processor.onaudioprocess = (e) => {
        if (ws.readyState === WebSocket.OPEN) {
            const float32Data = e.inputBuffer.getChannelData(0);

            // Convert Browser Float32 to Int16 PCM (Required by Server)
            const pcm16 = new Int16Array(float32Data.length);
            for (let i = 0; i < float32Data.length; i++) {
                pcm16[i] = Math.max(-1, Math.min(1, float32Data[i])) * 0x7FFF;
            }

            // Send binary PCM audio chunk to server
            ws.send(pcm16.buffer);
        }
    };

    source.connect(processor);
    processor.connect(audioCtx.destination);
};

// 3. Handle graceful shutdown
function stopRecording() {
    ws.send(JSON.stringify({ command: "stop" }));
}

연결 해제 및 오류 코드

연결이 거부되거나 끊어지면 WebSocket은 다음 특정 코드 중 하나로 종료됩니다:

종료 코드 이름 설명
1000 NORMAL_CLOSURE 스트림이 정상적으로 종료되었습니다. 사용량이 기록되었으며 적절히 환불되었습니다.
4001 MISSING_API_KEY ?api_key= 파라미터가 제공되지 않았거나 유효하지 않습니다.
4002 UNAUTHORIZED 유효하지 않은 API 키, 제한된 IP 또는 스트림을 시작/계속하기에 크레딧이 부족합니다.
4009 PAYLOAD_TOO_LARGE 256KB보다 큰 오디오 청크를 전송했습니다. 더 작은 버퍼로 스트리밍하세요.
4290 CONCURRENT_LIMIT 계정의 활성 WebSocket 연결이 너무 많습니다. 한도는 활성 스트림 1개입니다.
API 지원

API 관련 질문이나 문제는 다음 주소로 문의해 주세요: api@moknah.io.