К сожалению, чтобы настроить это, требуется несколько задач, поэтому вот они.
Создайте приложение .NET MAUI, я назвал свое AudioManagerTest.
Во-первых, мне нужно было настроить подпись пакета IoS.
Во-вторых, мне нужно было настроить info.plist:
Код: Выделить всё
NSMicrophoneUsageDescription
This app needs microphone access to allow for voice recognition and AI request processing.
LSRequiresIPhoneOS
UIDeviceFamily
1
2
UIRequiredDeviceCapabilities
arm64
UISupportedInterfaceOrientations
UIInterfaceOrientationPortrait
UIInterfaceOrientationLandscapeLeft
UIInterfaceOrientationLandscapeRight
UISupportedInterfaceOrientations~ipad
UIInterfaceOrientationPortrait
UIInterfaceOrientationPortraitUpsideDown
UIInterfaceOrientationLandscapeLeft
UIInterfaceOrientationLandscapeRight
XSAppIconAssets
Assets.xcassets/appicon.appiconset
Код: Выделить всё
[Register("AppDelegate")]
public class AppDelegate : MauiUIApplicationDelegate
{
protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
SetAudioSession();
return base.FinishedLaunching(application, launchOptions);
}
public bool SetAudioSession()
{
var audioSession = AVAudioSession.SharedInstance();
var err = audioSession.SetCategory(AVAudioSessionCategory.PlayAndRecord, AVAudioSessionCategoryOptions.AllowBluetooth |
AVAudioSessionCategoryOptions.AllowAirPlay | AVAudioSessionCategoryOptions.DefaultToSpeaker);
if (err != null)
return false;
err = audioSession.SetActive(true);
if (err != null)
return false;
return true;
}
}
Код: Выделить всё
using Microsoft.Maui.Controls;
using Plugin.Maui.Audio;
namespace AudioManagerTest
{
public partial class MainPage : ContentPage
{
int count = 0;
private IAudioManager _audioManager;
private IAudioStreamer? _audioStreamer;
private IAudioPlayer playerIsSleeping;
private List _audioBuffer;
public MainPage()
{
InitializeComponent();
}
public async Task StartIt()
{
try
{
_audioManager = new AudioManager();
_audioBuffer = new List();
_audioStreamer = _audioManager.CreateStreamer();
}
catch (Exception ex)
{
await SayIt("Error initializing audio manager: " + ex.Message);
return;
}
try
{
// Configure streaming options for optimal PCM16 format
_audioStreamer.Options.SampleRate = 16000;// 44100; // Standard sample rate
_audioStreamer.Options.Channels = ChannelType.Mono; // Mono for efficiency
_audioStreamer.Options.BitDepth = BitDepth.Pcm16bit; // PCM16 as requested
//await _audioStreamer.StartAsync();
}
catch (Exception ex)
{
await SayIt("Error starting audio streamer: " + ex.Message);
return;
}
playerIsSleeping = AudioManager.Current.CreatePlayer(await FileSystem.OpenAppPackageFileAsync("isAsleep.wav"));
playerIsSleeping.Play();
await SayIt("I am ready.");
}
private async Task SayIt(string text)
{
CancellationToken token = new CancellationToken();
//onTextOut(text);
await TextToSpeech.Default.SpeakAsync(text, cancelToken: token).ConfigureAwait(false);
}
private async void OnCounterClicked(object? sender, EventArgs e)
{
count++;
if (count == 1)
CounterBtn.Text = $"Clicked {count} time";
else
CounterBtn.Text = $"Clicked {count} times";
//SemanticScreenReader.Announce(CounterBtn.Text);
await StartIt();
}
}
}
Код: Выделить всё
isAsleep.wavПри первом развертывании и запуске он будет воспроизводить звуки после нажатия кнопки. Я считаю, что это связано с задержкой, поскольку пользователю нужно нажать кнопку.
Когда вы закомментируете строку: await _audioStreamer.StartAsync(), звуки будут воспроизводиться.
Опять же, это работает на Android. И если я прерву вывод и перезапущу, не закомментировав приведенную выше строку, иногда я смогу заставить ее работать.
Я экспериментировал с этим и не могу понять, почему IoS не позволяет воспроизводить ее.
Кто-нибудь знает, что происходит?
Подробнее здесь: https://stackoverflow.com/questions/798 ... and-starte
Мобильная версия