Мы пытаемся использовать распознаватель речи в Xamarin на Android, мы настроили основное действие так:
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity, IRecognitionListener
{
TextView textMessage;
private Button recButton;
private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
// get the resources from the layout
recButton = FindViewById<Button>(Resource.Id.btnRecord);
textMessage = FindViewById<TextView>(Resource.Id.message);
// check to see if we can actually record - if we can, assign the event to the button
string rec = Android.Content.PM.PackageManager.FeatureMicrophone;
if (rec != "android.hardware.microphone")
{
// no microphone, no recording. Disable the button and output an alert
var alert = new Android.Support.V7.App.AlertDialog.Builder(recButton.Context);
alert.SetTitle("You don't seem to have a microphone to record with");
alert.SetPositiveButton("OK", (sender, e) =>
{
textMessage.Text = "No microphone present";
recButton.Enabled = false;
return;
});
alert.Show();
}
else
{
mSpeechRecognizer = SpeechRecognizer.CreateSpeechRecognizer(this);
mSpeechRecognizer.SetRecognitionListener(this);
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech);
mSpeechRecognizerIntent.PutExtra(RecognizerIntent.ExtraCallingPackage, PackageName);
mSpeechRecognizerIntent.PutExtra(RecognizerIntent.ExtraPrompt, "Start Speaking Now!");
mSpeechRecognizerIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, this.Resources.Configuration.Locale.Language);
mSpeechRecognizerIntent.PutExtra(RecognizerIntent.ExtraMaxResults, 5);
Button StartListening = FindViewById<Button>(Resource.Id.btnRecord);
StartListening.Click += StartListening_Click;
RequestPermissionsManually();
}
}
private void RequestPermissionsManually()
{
List<string> permission = new List<string>();
if (CheckSelfPermission(Android.Manifest.Permission.Internet) != Permission.Granted)
permission.Add(Android.Manifest.Permission.Internet);
if (CheckSelfPermission(Android.Manifest.Permission.RecordAudio) != Permission.Granted)
permission.Add(Android.Manifest.Permission.RecordAudio);
if (permission.Count > 0)
{
string[] array = permission.ToArray();
RequestPermissions(array, array.Length);
}
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
{
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
void StartListening_Click(object sender, EventArgs e)
{
mSpeechRecognizer.StartListening(mSpeechRecognizerIntent);
}
public void OnError([GeneratedEnum] SpeechRecognizerError error)
{
}
public void OnResults(Bundle results)
{
IList<string> matches = results.GetStringArrayList(SpeechRecognizer.ResultsRecognition);
}
}
Изначально мы получали ошибку недостаточных привилегий, даже если у нас настроен манифест разрешений следующим образом:
использует разрешение android: name = "android.permission.RECORD_AUDIO"
использует разрешение android: name = "android.permission.INTERNET"
Мы добавили код, чтобы вручную запрашивать разрешения, которые переместили нас от ошибки достаточного разрешения к сетевой ошибке в перечислении SpeechRecognizerError.
Мы работаем в Visual Studio и версиях Xamarin:
Microsoft Visual Studio Community 2017 Версия 15.8.8
VisualStudio.15.Release / 15.8.8 + 28010.2048 Microsoft .NET Framework
Версия 4.7.03056
Xamarin 4.11.0.776 (d15-8 @ 1ae9b59d7) Расширение Visual Studio для
включить разработку для Xamarin.iOS и Xamarin.Android.
Xamarin Designer 4.15.9 (d000f568b) Расширение Visual Studio для
включить инструменты Xamarin Designer в Visual Studio.
Шаблоны Xamarin 1.1.116 (9619170) Шаблоны для сборки iOS,
Приложения для Android и Windows с Xamarin и Xamarin.Forms.
Xamarin.Android SDK 9.0.0.19 (HEAD / a8a3b0ec7) Xamarin.Android
Справочные сборки и поддержка MSBuild.
Xamarin.iOS и Xamarin.Mac SDK 12.0.0.15 (84552a4) Xamarin.iOS и
Справочные сборки Xamarin.Mac и поддержка MSBuild.
Мы запускаем это на эмуляторе: Android_Accelerated_x86_ORea (Android 8.1 - API 27).
Есть ли что-то простое, чего нам не хватает в отношении того, почему мы получаем эту сетевую ошибку?
Обновление:
Я сейчас попробовал приложение карты и хром в эмуляторе, и при выборе микрофона возникает та же проблема, и она не работает. Это похоже на микрофон на эмуляторе, есть ли настройка, которую нужно включить?