0 / 0 / 0
Регистрация: 16.06.2014
Сообщений: 2
1

Написать программу распознавания речи

16.06.2014, 17:38. Показов 2662. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Задача такова: правильно расписать программу на visual basic.net 2013, которая будет распознавать речь на русском. Есть исходный код написанный на c#, но я не могу перевести его в vb.net. Программу visual basic.net начал осваивать недавно, умею работать только на visual basic 6. Есть установленный microsoft sdk 11 и русская библиотека распознавания речи. Наличие microsoft kinect, не обязательный фактор.
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
using System;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using Microsoft.Speech.AudioFormat;
using Microsoft.Speech.Recognition;
 
#if KINECT
using Microsoft.Kinect;
#endif
 
 
namespace KinectSpeechRecognize
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region Fields
 
#if KINECT
        private KinectSensor _kinect;
#endif        
        private SpeechRecognitionEngine _speechRecognizer;
        private DispatcherTimer _readyTimer;
 
        #endregion // Fields
 
        #region .ctor
 
        public MainWindow()
        {
            InitializeComponent();
        }
 
        #endregion // .ctor
 
        #region Private methods
 
        private void InitializeSpeechEngine()
        {
            _speechRecognizer = CreateSpeechRecognizer();
 
            InitializeKinect();
#if !KINECT
            txtKinectStatus.Text = "kinect ISN't connected, default mic will be used";
#endif
 
            if (_speechRecognizer != null)
            {
                // NOTE: Need to wait 4 seconds for device to be ready to stream audio right after initialization
                _readyTimer = new DispatcherTimer();
                _readyTimer.Tick += ReadyTimerTick;
                _readyTimer.Interval = new TimeSpan(0, 0, 4);
                _readyTimer.Start();
 
                ReportSpeechStatus("initializing audio stream...");
            }
        }
 
        private void UninitializeSpeechEngine()
        {
#if KINECT
            if (_kinect != null)
            {
                _kinect.AudioSource.Stop();
                _kinect.Stop();
            }
#endif
            if (_speechRecognizer != null)
            {
                _speechRecognizer.RecognizeAsyncCancel();
                _speechRecognizer.RecognizeAsyncStop();
            }
 
            if (_readyTimer != null)
            {
                _readyTimer.Stop();
                _readyTimer = null;
            }
        }
 
        [Conditional("KINECT")]
        private void InitializeKinect()
        {
#if KINECT
            _kinect = KinectSensor.KinectSensors
                .Where(s => s.Status == KinectStatus.Connected)
                .FirstOrDefault();
 
            try
            {
                _kinect.Start();
                txtKinectStatus.Text = (_kinect != null) ? "kinect is connected" : "kinect ISN't connected, default mic will be used";
            }
            catch (Exception)
            {
                txtKinectStatus.Text = "kinect ISN't connected, default mic will be used";
            }
#endif
        }
 
        private SpeechRecognitionEngine CreateSpeechRecognizer()
        {
            RecognizerInfo ri = GetSpeechRecognizerInfo();
            if (ri == null)
            {
                MessageBox.Show(@"There was a problem initializing Speech Recognition. Ensure you have the Microsoft Speech SDK installed.", "Failed to load Speech SDK", MessageBoxButton.OK, MessageBoxImage.Error);
                this.Close();
                return null;
            }
 
            SpeechRecognitionEngine sre;
            try
            {
                sre = new SpeechRecognitionEngine(ri.Id);
            }
            catch
            {
                MessageBox.Show(@"There was a problem initializing Speech Recognition. Ensure you have the Microsoft Speech SDK installed and configured.", "Failed to load Speech SDK", MessageBoxButton.OK, MessageBoxImage.Error);
                this.Close();
                return null;
            }
 
            var commands = new Choices();
            commands.Add("up");
            commands.Add("down");
            commands.Add("left");
            commands.Add("right");
            commands.Add("exit");
 
            var gb = new GrammarBuilder(commands) { Culture = ri.Culture };
            //gb.Append(commands);
 
            // Create the actual Grammar instance, and then load it into the speech recognizer.
            sre.LoadGrammar(new Grammar(gb));
            sre.SpeechRecognized += SreSpeechRecognized;
            sre.SpeechHypothesized += SreSpeechHypothesized;
            sre.SpeechRecognitionRejected += SreSpeechRecognitionRejected;
 
            return sre;
        }
 
        private static RecognizerInfo GetSpeechRecognizerInfo()
        {
            return SpeechRecognitionEngine.InstalledRecognizers()
                .Where(ri => string.Equals(ri.Culture.Name, "en-US", StringComparison.InvariantCultureIgnoreCase))
                .FirstOrDefault();
        }
 
        private void ReadyTimerTick(object sender, EventArgs e)
        {
            Start();
            ReportSpeechStatus("ready to recognize speech!");
 
            _readyTimer.Stop();
            _readyTimer = null;
        }
 
        private void Start()
        {
#if KINECT
            if (_kinect != null)
            {
                var audioSource = _kinect.AudioSource;
                audioSource.BeamAngleMode = BeamAngleMode.Adaptive;
                var kinectStream = audioSource.Start();
 
                _speechRecognizer.SetInputToAudioStream(
                    kinectStream, new SpeechAudioFormatInfo(EncodingFormat.Pcm, 16000, 16, 1, 32000, 2, null));
            }
            else
            {
                _speechRecognizer.SetInputToDefaultAudioDevice();
            }
#else
            _speechRecognizer.SetInputToDefaultAudioDevice();
#endif            
            _speechRecognizer.RecognizeAsync(RecognizeMode.Multiple);
        }
 
        private void ReportSpeechStatus(string format, params object[] args)
        {
            ReportSpeechStatus(string.Format(format, args));
        }
 
        private void ReportSpeechStatus(string status)
        {
            Dispatcher.BeginInvoke(new Action(() => { txtCommand.Text = status; }), DispatcherPriority.Normal);
        }
 
        private void RejectSpeech(RecognitionResult result)
        {
            ReportSpeechStatus("rejected: {0} {1:0.000}", result == null ? string.Empty : result.Text.ToUpper(), result.Confidence);
        }
 
        private void ActivateStoryboard(string storyboardName)
        {
            var sb = this.Resources[storyboardName] as Storyboard;
            if (sb == null)
            {
                Debug.WriteLine("Storyboard with name '{0}' not found in window's resources.", storyboardName);
                return;
            }
 
            sb.Begin(this);
        }
 
        #endregion // Private methods
 
        #region Events handlers
 
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            InitializeSpeechEngine();
        }
 
        private void Window_Unloaded(object sender, RoutedEventArgs e)
        {
            UninitializeSpeechEngine();
        }
 
        private void SreSpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            if (e.Result.Confidence < 0.7)
            {
                RejectSpeech(e.Result);
                return;
            }
 
            Action handler = null;
            switch (e.Result.Text.ToUpperInvariant())
            {
                case "UP":
                case "DOWN":
                case "LEFT":
                case "RIGHT":
                    handler = () => { ActivateStoryboard(e.Result.Text.ToUpperInvariant()); };
                    break;
                case "EXIT":
                    handler = () => { this.Close(); };
                    break;
                default:
                    break;
            }
 
            ReportSpeechStatus(string.Format("recognized: {0} {1:0.000}", e.Result.Text.ToUpper(), e.Result.Confidence));
 
            if (handler != null)
            {
                Dispatcher.BeginInvoke(handler, DispatcherPriority.Normal);
            }
        }
 
        private void SreSpeechHypothesized(object sender, SpeechHypothesizedEventArgs e)
        {
            ReportSpeechStatus("hypothesized: {0} {1:0.000}", e.Result.Text.ToUpper(), e.Result.Confidence);
        }
 
        private void SreSpeechRecognitionRejected(object sender, SpeechRecognitionRejectedEventArgs e)
        {
            RejectSpeech(e.Result);
        }
 
        #endregion // Events handlers
    }
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
16.06.2014, 17:38
Ответы с готовыми решениями:

Ошибка распознавания речи: Распознаватель не установлен
Господа В чем проблема?

Написать программу распознавания речи
я чайник в программировании конечно еше тот бейсик тока знал так во лазил по форумам напоролся на...

MFCC + ANN - написать программу распознавания речи
Добрый день ! Пытаюсь написать программу распознавания своей речи, исключительно для своих личных...

ПО для распознавания речи
Понадобилась прога по сабжу. По указанным ссылка на ifolder скачать прогу не удалось(( У кого...

2
649 / 601 / 92
Регистрация: 19.03.2012
Сообщений: 1,128
16.06.2014, 18:05 2
Ralf225, вот так это выглядит на VB.NET:
Кликните здесь для просмотра всего текста
VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
Imports System
Imports System.Diagnostics
Imports System.Linq
Imports System.Windows
Imports System.Windows.Media.Animation
Imports System.Windows.Threading
Imports Microsoft.Speech.AudioFormat
Imports Microsoft.Speech.Recognition
Imports Microsoft.Kinect
Namespace KinectSpeechRecognize
    Public Partial Class MainWindow
        Inherits Window
        Private _kinect As KinectSensor
        Private _speechRecognizer As SpeechRecognitionEngine
        Private _readyTimer As DispatcherTimer
        Public Sub New()
            InitializeComponent()
        End Sub
        Private Sub InitializeSpeechEngine()
            _speechRecognizer = CreateSpeechRecognizer()
            InitializeKinect()
            txtKinectStatus.Text = "kinect ISN't connected, default mic will be used"
            If _speechRecognizer <> Nothing Then
                _readyTimer = New DispatcherTimer()
                _readyTimer.Tick += ReadyTimerTick
                _readyTimer.Interval = New TimeSpan(0, 0, 4)
                _readyTimer.Start()
                ReportSpeechStatus("initializing audio stream...")
            End If
        End Sub
        Private Sub UninitializeSpeechEngine()
            If _kinect <> Nothing Then
                _kinect.AudioSource.[Stop]()
                _kinect.[Stop]()
            End If
            If _speechRecognizer <> Nothing Then
                _speechRecognizer.RecognizeAsyncCancel()
                _speechRecognizer.RecognizeAsyncStop()
            End If
            If _readyTimer <> Nothing Then
                _readyTimer.[Stop]()
                _readyTimer = Nothing
            End If
        End Sub
        <Conditional("KINECT")> _
        Private Sub InitializeKinect()
            _kinect = KinectSensor.KinectSensors.Where(Function(s As ) s.Status = KinectStatus.Connected).FirstOrDefault()
            Try
                _kinect.Start()
                txtKinectStatus.Text = If((_kinect <> Nothing), "kinect is connected", "kinect ISN't connected, default mic will be used")
            Catch generatedExceptionName As Exception
                txtKinectStatus.Text = "kinect ISN't connected, default mic will be used"
            End Try
        End Sub
        Private Function CreateSpeechRecognizer() As SpeechRecognitionEngine
            Dim ri As RecognizerInfo = GetSpeechRecognizerInfo()
            If ri = Nothing Then
                MessageBox.Show("There was a problem initializing Speech Recognition. Ensure you have the Microsoft Speech SDK installed.", "Failed to load Speech SDK", MessageBoxButton.OK, MessageBoxImage.[Error])
                Me.Close()
                Return Nothing
            End If
            Dim sre As SpeechRecognitionEngine
            Try
                sre = New SpeechRecognitionEngine(ri.Id)
            Catch
                MessageBox.Show("There was a problem initializing Speech Recognition. Ensure you have the Microsoft Speech SDK installed and configured.", "Failed to load Speech SDK", MessageBoxButton.OK, MessageBoxImage.[Error])
                Me.Close()
                Return Nothing
            End Try
            Dim commands As var = New Choices()
            commands.Add("up")
            commands.Add("down")
            commands.Add("left")
            commands.Add("right")
            commands.Add("exit")
            Dim gb As var = New GrammarBuilder(commands) With { _
                .Culture = ri.Culture _
            }
            sre.LoadGrammar(New Grammar(gb))
            sre.SpeechRecognized += SreSpeechRecognized
            sre.SpeechHypothesized += SreSpeechHypothesized
            sre.SpeechRecognitionRejected += SreSpeechRecognitionRejected
            Return sre
        End Function
        Private Shared Function GetSpeechRecognizerInfo() As RecognizerInfo
            Return SpeechRecognitionEngine.InstalledRecognizers().Where(Function(ri As ) String.Equals(ri.Culture.Name, "en-US", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault()
        End Function
        Private Sub ReadyTimerTick(sender As Object, e As EventArgs)
            Start()
            ReportSpeechStatus("ready to recognize speech!")
            _readyTimer.[Stop]()
            _readyTimer = Nothing
        End Sub
        Private Sub Start()
            If _kinect <> Nothing Then
                Dim audioSource As var = _kinect.AudioSource
                audioSource.BeamAngleMode = BeamAngleMode.Adaptive
                Dim kinectStream As var = audioSource.Start()
                _speechRecognizer.SetInputToAudioStream(kinectStream, New SpeechAudioFormatInfo(EncodingFormat.Pcm, 16000, 16, 1, 32000, 2, _
                    Nothing))
            Else
                _speechRecognizer.SetInputToDefaultAudioDevice()
            End If
            _speechRecognizer.SetInputToDefaultAudioDevice()
            _speechRecognizer.RecognizeAsync(RecognizeMode.Multiple)
        End Sub
        Private Sub ReportSpeechStatus(format As String, ParamArray args As Object())
            ReportSpeechStatus(String.Format(format, args))
        End Sub
        Private Sub ReportSpeechStatus(status As String)
            Dispatcher.BeginInvoke(New Action(Function() Do
                txtCommand.Text = status
            End Function), DispatcherPriority.Normal)
        End Sub
        Private Sub RejectSpeech(result As RecognitionResult)
            ReportSpeechStatus("rejected: {0} {1:0.000}", If(result = Nothing, String.Empty, result.Text.ToUpper()), result.Confidence)
        End Sub
        Private Sub ActivateStoryboard(storyboardName As String)
            Dim sb As var = TryCast(Me.Resources(storyboardName), Storyboard)
            If sb = Nothing Then
                Debug.WriteLine("Storyboard with name '{0}' not found in window's resources.", storyboardName)
                Return
            End If
            sb.Begin(Me)
        End Sub
        Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
            InitializeSpeechEngine()
        End Sub
        Private Sub Window_Unloaded(sender As Object, e As RoutedEventArgs)
            UninitializeSpeechEngine()
        End Sub
        Private Sub SreSpeechRecognized(sender As Object, e As SpeechRecognizedEventArgs)
            If e.Result.Confidence < 0.7 Then
                RejectSpeech(e.Result)
                Return
            End If
            Dim handler As Action = Nothing
            Select Case e.Result.Text.ToUpperInvariant()
                Case "UP", "DOWN", "LEFT", "RIGHT"
                    handler = Function() Do
                        ActivateStoryboard(e.Result.Text.ToUpperInvariant())
                    End Function
                    Exit Select
                Case "EXIT"
                    handler = Function() Do
                        Me.Close()
                    End Function
                    Exit Select
                Case Else
                    Exit Select
            End Select
            ReportSpeechStatus(String.Format("recognized: {0} {1:0.000}", e.Result.Text.ToUpper(), e.Result.Confidence))
            If handler <> Nothing Then
                Dispatcher.BeginInvoke(handler, DispatcherPriority.Normal)
            End If
        End Sub
        Private Sub SreSpeechHypothesized(sender As Object, e As SpeechHypothesizedEventArgs)
            ReportSpeechStatus("hypothesized: {0} {1:0.000}", e.Result.Text.ToUpper(), e.Result.Confidence)
        End Sub
        Private Sub SreSpeechRecognitionRejected(sender As Object, e As SpeechRecognitionRejectedEventArgs)
            RejectSpeech(e.Result)
        End Sub
    End Class
End Namespace

P.S.: работоспособность не установлена.
3
0 / 0 / 0
Регистрация: 16.06.2014
Сообщений: 2
17.06.2014, 06:45  [ТС] 3
Спасибо за подробный код Nachrichter, буду разбираться дальше.
0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
17.06.2014, 06:45
Помогаю со студенческими работами здесь

Ускорение распознавания речи
Недавно начал учить распознавание речи в Python, есть код: import speech_recognition as sr def...

Система распознавания речи
Хочу написать программу которая работала бы как Google Voice Search (Голосовой поиск Гугл) только...

Написание системы распознавания речи!
Привет форумчанам! Задумался я над интересно темой: Распознавание речи.Тема довольна...

Динамический вывод распознавания речи
Как можно сделать динамический вывод голоса в текст? То есть во время разговора оно заполняет...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru