我正在使用用于在带有属性Label
的 UI 上显示 HTML 数据。TextType="Html"
该功能运行良好,并且在 UI HTML 内容上被转换为普通文本。
我还使用Xamarin Essentials
. 当 TTS 功能启动时,我使用span 属性突出显示相应的文本。
当 TTS 功能启动时,普通文本被转换为 HTML 数据。我如何解决这个问题?
截屏:
我在这里上传了一个示例项目以供参考。
这将是一个预期的效果,因为字符串的内容是 html 格式。作为一种解决方法,您可以使用Regex获取 html 的内容。
public static string GetHtmlText(string html)
{
html = System.Text.RegularExpressions.Regex.Replace(html, @"<\/*[^<>]*>", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
html = html.Replace("\r\n", "").Replace("\r", "").Replace(" ", "").Replace(" ", "").Replace("\n\n\n", "\n");
return html;
}
所以你可以改进如下代码:
public partial class MainPage : ContentPage
{
string[] strList;
public List<ChapterDetails> chapterDetails { get; set; }
public MainPage()
{
InitializeComponent();
//normal text
//string content = "Each platform supports different locales,\n to speak back text in different languages and accents.\n Platforms have different codes and ways of specifying the locale, \n which is why Xamarin provides a cross-platform Locale class and a way to query them with GetLocalesAsync.\n ";
//html text from epub file
chapterDetails = new List<ChapterDetails>();
string fileName = "Alices-Adventures-in-wonderland.epub";
var assembly = typeof(MainPage).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{fileName}");
EpubBook epubBook = EpubReader.ReadBook(stream);
foreach (EpubChapter chapter in epubBook.Chapters)
{
chapterDetails.Add(new ChapterDetails() { title = chapter.Title, htmlData = chapter.HtmlContent, subChapters = chapter.SubChapters });
}
string content = GetHtmlText(chapterDetails[0].htmlData);
label.Text = content;
string str = ".";
char character = char.Parse(str);
string str2 = ",";
char character2 = char.Parse(str2);
string str3 = "\n";
char character3 = char.Parse(str3);
strList = content.Split(new char[] { character, character2 , character3});
}
public static string GetHtmlText(string html)
{
html = System.Text.RegularExpressions.Regex.Replace(html, @"<\/*[^<>]*>", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
html = html.Replace("\r\n", "").Replace("\r", "").Replace(" ", "").Replace(" ", "").Replace("\n\n\n", "\n");
return html;
}
private async void ClickedButton(object Sender, EventArgs args)
{
for (int i = 0; i < strList.Length; i++)
{
if(!string.IsNullOrEmpty(strList[i]))
{
string content = strList[i];
var formattedString = new FormattedString();
for (int j = 0; j < strList.Length; j++)
{
if (i == j)
{
formattedString.Spans.Add(new Span { Text = strList[j], ForegroundColor = Color.Black, BackgroundColor = Color.Gray });
}
else
{
formattedString.Spans.Add(new Span { Text = strList[j], ForegroundColor = Color.Black, });
}
}
label.FormattedText = formattedString;
label.TextType = TextType.Html;
await TextToSpeech.SpeakAsync(content);
}
}
}
}
注意:这样css的样式将不再起作用。您需要自己在 span 中设置样式(字体或颜色)。