You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Unity中如何获取操作系统的语音语言?

获取Unity中操作系统的语音输入语言

Unity的Application.systemLanguage返回的是系统UI显示语言,和语音输入的默认语言确实可能不一致,需要针对不同平台调用原生API来获取:

Windows平台

通过.NET的System.Speech命名空间调用语音识别引擎接口,获取默认语音语言:

using System.Speech.Recognition;

public string GetWindowsSpeechLanguage()
{
    using (var recognizer = new SpeechRecognitionEngine())
    {
        // 返回格式如"zh-CN"、"en-US"
        return recognizer.RecognizerInfo.Culture.Name;
    }
}

注意:Unity项目需将Player Settings中的.NET版本设置为.NET 4.x Equivalent,否则无法引用System.Speech。

macOS平台

编写Objective-C原生代码,调用NSSpeechRecognizer获取默认语音语言,再通过Unity的DllImport调用:

原生代码(.mm文件)

#import <AppKit/AppKit.h>

extern "C" {
    const char* GetMacSpeechLanguage()
    {
        NSSpeechRecognizer* recognizer = [[NSSpeechRecognizer alloc] init];
        NSString* langCode = recognizer.defaultLanguage;
        return [langCode UTF8String];
    }
}

Unity C#调用

[DllImport("__Internal")]
private static extern string GetMacSpeechLanguage();

public string GetCurrentMacSpeechLang()
{
    return GetMacSpeechLanguage();
}

Android平台

通过Unity的AndroidJavaClass调用Android原生SpeechRecognizer相关API:

public string GetAndroidSpeechLanguage()
{
    AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
    
    AndroidJavaClass speechIntentClass = new AndroidJavaClass("android.content.Intent");
    string action = speechIntentClass.GetStatic<string>("ACTION_RECOGNIZE_SPEECH");
    AndroidJavaObject intent = new AndroidJavaObject("android.content.Intent", action);
    
    // 获取默认语音语言参数
    AndroidJavaObject extras = intent.Call<AndroidJavaObject>("getExtras");
    string defaultLang = extras.Call<string>("getString", "android.speech.extra.LANGUAGE");
    
    return defaultLang ?? "en-US"; // 无返回时默认英文
}

iOS平台

调用iOS的SFSpeechRecognizer框架获取语音语言,同样需要原生代码配合:

原生代码(.mm文件)

#import <Speech/Speech.h>

extern "C" {
    const char* GetiOSSpeechLanguage()
    {
        SFSpeechRecognizer* recognizer = [[SFSpeechRecognizer alloc] init];
        NSString* langCode = recognizer.locale.localeIdentifier;
        return [langCode UTF8String];
    }
}

Unity C#调用

[DllImport("__Internal")]
private static extern string GetiOSSpeechLanguage();

public string GetCurrentiOSSpeechLang()
{
    return GetiOSSpeechLanguage();
}

注意:iOS项目需在Info.plist中添加NSSpeechRecognitionUsageDescription权限描述,否则会被系统拒绝。


内容的提问来源于stack exchange,提问作者Miguel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 02:57:44