Tutorial: Building Conversational NPCs in Unity 6 with MorVoice SDK (Zero-Latency Setup)
الكأس المقدسة للألعاب الحديثة هي 'Smart NPC'. بينما حلت نماذج LLM جزء الدماغ، ظل جزء الصوت يمثل عقبة.
يوضح لك هذا البرنامج التعليمي كيفية تنفيذ **MorVoice Streaming SDK** في Unity 6. سنحقق زمن انتقال للاستجابة الصوتية أقل من 200 مللي ثانية.
المتطلبات الأساسية
- Unity 2022.3 LTS or higher (Unity 6 recommended)
- MorVoice SDK (Install via Package Manager: https://npm.morvoice.com)
- An API Key from dashboard.morvoice.com
- A basic NPC GameObject with an AudioSource componentالبنية: خط أنابيب البث
لا تحفظ الصوت على القرص. سنقوم ببث بيانات PCM الخام مباشرة من مخزن WebSocket إلى مخزن AudioSource.
الخطوة 1: وحدة التحكم الصوتية للشخصية
قم بإنشاء نص برمجي جديد باسم `NPCVoiceController.cs` وألحقه بشخصيتك.
using UnityEngine;
using MorVoice.SDK;
using System.Collections;
public class NPCVoiceController : MonoBehaviour
{
[SerializeField] private string voiceId = "orc_warrior_v2";
private MorVoiceClient _client;
private AudioSource _audioSource;
void Start()
{
_client = new MorVoiceClient(ApiKey.LoadFromEnv());
_audioSource = GetComponent<AudioSource>();
}
public async void Speak(string text)
{
// 1. Start the stream. This returns immediately (active connection)
var stream = await _client.StreamSpeechAsync(text, voiceId);
// 2. Prepare a streaming AudioClip (Unity 2022+ feature)
var clip = AudioClip.Create("VoiceStream", 44100 * 60, 1, 44100, true,
(float[] data) => stream.ReadBuffer(data));
_audioSource.clip = clip;
_audioSource.Play();
}
}الخطوة 2: تكامل مزامنة الشفاه
الصوت ليس كافياً؛ يجب أن يتحرك الفم. يرسل MorVoice أحداث 'viseme' (أشكال الفم) إلى جانب أجزاء الصوت.
// Inside Speak() method, subscribe to viseme events
stream.OnViseme += (visemeCode, duration) => {
// Map MorVoice viseme codes to your character's BlendShapes
// Example: Code 4 = 'Ah' sound -> Set BlendShape 'MouthOpen' to 100
float intensity = 100f;
SkinnedMeshRenderer.SetBlendShapeWeight(visemeCode, intensity);
// Auto-close mouth after duration
StartCoroutine(ResetMouth(visemeCode, duration));
};نصائح التحسين
1. تسخين الاتصال
Establish the WebSocket connection when the player enters the room, not when they start talking. This saves the initial SSL handshake time (approx 100ms).
2. تخزين العبارات الشائعة
بالنسبة للردود القياسية مثل 'مرحباً'، قم بتوليدها مرة واحدة وتخزينها محلياً.
المزالق الشائعة
❌ NEVER call .ToArray() on the stream. That waits for the full audio to download.
✅ ALWAYS use the streaming callback or buffer reader.
❌ WARNING: Don't use standard HTTP requests. They block the main thread in WebGL builds.
✅ Use the async/await pattern shown above.الخلاصة
مع هذا الإعداد، يمكن لشخصيات NPC مقاطعة اللاعبين والتفاعل مع أحداث اللعبة في الوقت الفعلي.
Download the complete Unity Project example from our GitHub repository.