using System;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Threading;
using NewLife;
using NewLife.XCoder.Services;
namespace NewLife.XCoder.Tools.Voice;
/// <summary>网络语音播报工具</summary>
public partial class VoiceNotifyToolView : UserControl
{
private VoiceNotifyListener? _listener;
/// <summary>实例化</summary>
public VoiceNotifyToolView()
{
InitializeComponent();
StartButton.Click += (_, _) => Start();
StopButton.Click += (_, _) => Stop();
SendButton.Click += (_, _) => Send();
ClearButton.Click += (_, _) => LogBox.Text = "";
ExportButton.Click += (_, _) => _ = ExportAsync();
DetachedFromVisualTree += (_, _) => Stop();
}
private void Start()
{
if (_listener != null) return;
var listener = new VoiceNotifyListener { Group = GroupBox.Text ?? "" };
try
{
listener.Start(PortBox.Text.ToInt());
}
catch (Exception ex)
{
SetStatus("监听失败:" + ex.Message, true);
return;
}
listener.Received += OnReceived;
_listener = listener;
PortBox.Text = listener.Port.ToString();
StartButton.IsEnabled = false;
StopButton.IsEnabled = true;
SetStatus($"监听中 · 端口 {listener.Port}", false);
}
private void Stop()
{
var listener = _listener;
if (listener == null) return;
_listener = null;
listener.Received -= OnReceived;
try { listener.Stop(); } catch { }
StartButton.IsEnabled = true;
StopButton.IsEnabled = false;
SetStatus("已停止", false);
}
private void Send()
{
var text = SendBox.Text;
if (text.IsNullOrEmpty()) return;
// 未启动时先给一个默认端口,便于收发自测
if (PortBox.Text.ToInt() <= 0) PortBox.Text = "24299";
var group = GroupBox.Text ?? "";
if (group.IsNullOrEmpty()) group = "239.255.42.99";
try
{
VoiceNotifyListener.Send(group, PortBox.Text.ToInt(), text!);
}
catch (Exception ex)
{
SetStatus("发送失败:" + ex.Message, true);
}
}
private void OnReceived(Object? sender, VoiceNotifyEventArgs e)
{
var line = $"{DateTime.Now:HH:mm:ss} {e.RemoteEndPoint} [{e.Message.Type}] {e.Message.Text}";
Dispatcher.UIThread.Post(() =>
{
LogBox.Text = (LogBox.Text.IsNullOrEmpty() ? line : LogBox.Text + Environment.NewLine + line);
});
}
private async Task ExportAsync()
{
if (LogBox.Text.IsNullOrEmpty())
{
SetStatus("没有可导出的记录", true);
return;
}
var name = await TextLogExporter.SaveAsync(this, "导出语音播报记录", "voice-notify.txt", LogBox.Text);
SetStatus(name == null ? "已取消" : "已导出:" + name, false);
}
private void SetStatus(String text, Boolean error)
{
StatusText.Text = NewLife.XCoder.Services.LocalizationService.Translate(text);
StatusText.Classes.Set("error", error);
StatusText.Classes.Set("ok", !error);
}
}
|