Текст в речь при освещении текущего словаC#

Место общения программистов C#
Ответить
Anonymous
 Текст в речь при освещении текущего слова

Сообщение Anonymous »

Я пытаюсь написать простое приложение, используя C#, которое будет читать текст в RichTextbox и Hightlights каждое слово, как оно читается. < /p>
Я использую < /p>
private SpeechSynthesizer synthesizer;
< /code>
Но когда он входит в код Speakprogress, чтобы сделать выделение, он никогда не работает. < /p>
кто -нибудь успешно видел это? Может, использовать другую библиотеку? < /P>
Вот мой код: < /p>
using System;
using System.Speech.Synthesis;
using System.Windows.Forms;
using System.Drawing;
using System.Linq;

namespace TextToSpeechApp
{
public partial class Form1 : Form
{
private SpeechSynthesizer synthesizer;
private string[] words;
private int currentWordIndex = -1;
private RichTextBox richTextBox;
private Timer highlightTimer;
private int currentCharPosition = 0;

public Form1()
{
InitializeComponent();
synthesizer = new SpeechSynthesizer();
synthesizer.SpeakStarted += Synthesizer_SpeakStarted;
synthesizer.SpeakCompleted += Synthesizer_SpeakCompleted;

// Initialize timer for highlighting
highlightTimer = new Timer
{
Interval = 100 // Adjust based on speech speed
};
highlightTimer.Tick += HighlightTimer_Tick;
}

private void InitializeComponent()
{
this.Text = "Text to Speech Reader";
this.Size = new Size(600, 400);
this.StartPosition = FormStartPosition.CenterScreen;

richTextBox = new RichTextBox
{
Location = new Point(10, 10),
Size = new Size(560, 300),
Font = new Font("Arial", 12),
Text = "Enter text here to be read aloud word by word."
};

Button readButton = new Button
{
Text = "Read Aloud",
Location = new Point(10, 320),
Size = new Size(100, 30)
};
readButton.Click += ReadButton_Click;

Button stopButton = new Button
{
Text = "Stop",
Location = new Point(120, 320),
Size = new Size(100, 30)
};
stopButton.Click += StopButton_Click;

this.Controls.Add(richTextBox);
this.Controls.Add(readButton);
this.Controls.Add(stopButton);
}

private void ReadButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(richTextBox.Text))
{
MessageBox.Show("Please enter some text to read.");
return;
}

// Reset state
synthesizer.SpeakAsyncCancelAll();
highlightTimer.Stop();
ResetHighlighting();
currentWordIndex = -1;
currentCharPosition = 0;

// Split text into words
words = richTextBox.Text.Split(new[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);

// Start speech
synthesizer.SpeakAsync(richTextBox.Text);
highlightTimer.Start();
}

private void StopButton_Click(object sender, EventArgs e)
{
synthesizer.SpeakAsyncCancelAll();
highlightTimer.Stop();
ResetHighlighting();
}

private void Synthesizer_SpeakStarted(object sender, SpeakStartedEventArgs e)
{
currentWordIndex = -1;
currentCharPosition = 0;
}

private void Synthesizer_SpeakCompleted(object sender, SpeakCompletedEventArgs e)
{
highlightTimer.Stop();
ResetHighlighting();
}

private void HighlightTimer_Tick(object sender, EventArgs e)
{
if (currentWordIndex >= words.Length - 1)
{
highlightTimer.Stop();
return;
}

// Find the next word's position
string text = richTextBox.Text;
int wordStart = currentCharPosition;
while (wordStart < text.Length && char.IsWhiteSpace(text[wordStart]))
{
wordStart++;
}

if (wordStart >= text.Length)
{
highlightTimer.Stop();
ResetHighlighting();
return;
}

// Find word end
int wordEnd = wordStart;
while (wordEnd < text.Length && !char.IsWhiteSpace(text[wordEnd]))
{
wordEnd++;
}

// Highlight the word
this.Invoke((MethodInvoker)delegate
{
ResetHighlighting();
richTextBox.SelectionStart = wordStart;
richTextBox.SelectionLength = wordEnd - wordStart;
richTextBox.SelectionBackColor = Color.Yellow;
});

currentWordIndex++;
currentCharPosition = wordEnd;

// Adjust timer interval based on word length (approximate)
highlightTimer.Interval = EstimateWordDuration(words[currentWordIndex]);
}

private int EstimateWordDuration(string word)
{
// Rough estimate: 100ms per character, minimum 200ms, maximum 800ms
int duration = word.Length * 100;
return Math.Max(200, Math.Min(800, duration));
}

private void ResetHighlighting()
{
this.Invoke((MethodInvoker)delegate
{
richTextBox.SelectionStart = 0;
richTextBox.SelectionLength = richTextBox.Text.Length;
richTextBox.SelectionBackColor = Color.White;
});
}

[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}


Подробнее здесь: https://stackoverflow.com/questions/797 ... rrent-word
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»