Пример #1
0
        public async IAsyncEnumerable <Sample[]> EnumerateSamplesAsync(InputOption option, [EnumeratorCancellation] CancellationToken token = default)
        {
            using var pcmStream = new WaveFileReader("G:\\test.wav");
            //using var pcmStream = WaveFormatConversionStream.CreatePcmStream(audio);
            option.SamplingFrequency = pcmStream.WaveFormat.SampleRate;
            var bytesCount = samplesBatchSize * pcmStream.BlockAlign;
            var buffer     = new byte[bytesCount];
            //if pcmStream.BitsPerSample == 16 && pcmStream.Channels == 1
            Func <byte[], int, float[]> getValues = Get16BitMono;

            while (pcmStream.Position < pcmStream.Length)
            {
                int bytesRead = await pcmStream.ReadAsync(buffer, 0, buffer.Length, token);

                if (bytesRead == 0)
                {
                    continue;
                }

                var samples = new Sample[bytesRead / pcmStream.BlockAlign];
                for (var i = 0; i < samples.Length; i++)
                {
                    var values = getValues(buffer, i * pcmStream.BlockAlign);
                    samples[i] = new Sample(values);
                }
                yield return(samples);

                await Task.Delay(50);
            }
        }
Пример #2
0
        private static async IAsyncEnumerable <RecognizeRequest> GenerateRequestStream(string filename, string model)
        {
            yield return(new RecognizeRequest {
                Config = new RecognitionConfig {
                    Model = new Model {
                        Id = model
                    },
                    Auth = new Auth {
                        ClientId = "ClientId",
                        DomainId = "DomainId",
                        ApiKey = "ApiKey"
                    }
                }
            });

            using var reader = new WaveFileReader(filename);
            int bytesPerSecond = reader.WaveFormat.AverageBytesPerSecond;
            var buffer         = new byte[bytesPerSecond];

            while (reader.Position < reader.Length)
            {
                int bytesRead = await reader.ReadAsync(buffer, 0, bytesPerSecond);

                if (bytesRead > 0)
                {
                    yield return(new RecognizeRequest {
                        Sound = new Sound {
                            Samples = Google.Protobuf.ByteString.CopyFrom(buffer)
                        }
                    });

                    Thread.Sleep(1000);
                }
            }

            yield return(new RecognizeRequest {
                Finish = new Finish()
            });
        }