NAudio Converting to PCM? - c#

Using the SetOutputToWaveFile method in the SpeechSynthesizer class, I included a SpeechAudioFormatInfo class with these parameters
new SpeechAudioFormatInfo(EncodingFormat.Pcm, 10000, 16, 1, 16000, 2, null);
My intent is to get the output to be 10kHz signed 16-bit little endian headerless raw mono PCM, and am now trying to understand how to harness NAudio to do that. I tried to base code on change wav file ( to 16KHz and 8bit ) with using NAudio with WaveFormat and WaveConversionStream but am not getting the output I need. Can anyone refer me to working sample code?
Thanks.

Related

How to extract image from TCP Stream

I need your help.
I was creating an application in c# that converts the data from the IP camera to an image (JPEG).
I was able to convert the image using the below code:
hex = "FFD8FFDB008400130D0F1.........";/// supply this with the attached hex dump.
byte[] image = HexString2Bytes(hex);
File.WriteAllBytes("visio.png", image);
Process.Start("visio.png");
private static byte[] HexString2Bytes(string hexString)
{
int bytesCount = (hexString.Length) / 2;
byte[] bytes = new byte[bytesCount];
for (int x = 0; x < bytesCount; ++x)
{
bytes[x] = Convert.ToByte(hexString.Substring(x * 2, 2), 16);
}
return bytes;
}
Sometimes I get a better image as expected:https://ibb.co/pxrwn6p
but sometimes I get a distorted image after converting https://ibb.co/9twx5ZT.
I was wondering if there is a problem with the conversion or the way I save the image.
because as per the supplier what I need to do is to directly save the image from the stream.
but since I receive it as a byte and I still need to convert it maybe there is something wrong with my codes.
the image also starts with ÿØÿÛ FF D8 and ends with ÿ Ùÿÿÿÿ (FF D9 FF FF FF FF)
here's the hex dump from their sample app:
https://drive.google.com/file/d/1CMlQ0xaVjM0jfU5A4MB-_HwK54dUMTOr/view?usp=sharing
using their test application the image can be captured and converted the image perfectly.
captured image using their application:https://ibb.co/2KgyLTc
using the hex from the sniff and convert it using my code:
converted image using my code:https://ibb.co/G0WMjht
sample source code:
please bare with my codes because currently this is only my test app before integrating this feature to another app.
https://drive.google.com/file/d/1Ux7zsR39IVNyd1wrBxQPQKA6yM4YnwJN/view?usp=sharing
Thank You in advance.
Looking at the hex-dump it looks like some kind of XML file with embedded image data. Trying to convert this directly to an image will most likely not work, you would need to parse the XML-data to extract the actual image file. But it looks like you have a valid Jpeg header, so I would guess you have found the start of the image at least. But you probably also need to check the length property from the XML-data to find the length of the image-data block.
However, the datablock looks like it contains large sections of zeros, this should not be present in a jpeg file, so it might indicate some data corruption. Possibly from the way the network data is captured.
I would expect cameras to use some higher level protocol than raw TCP. Like Real Time Streaming Protocol, GigE vision, or mjpeg over http. I have not seen any camera that require you to process a raw TCP streams. But since you do not show how the data is fetched it is difficult to tell if there is any mistakes in that code.

send array of bytes to System.Media.SoundPlayer in c#

I want send string byte to speaker something like this:
byte[] bt = {12,32,43,74,23,53,24,54,234,253,153};// example array
var ms = new MemoryStream(bt);
var sound = new System.Media.SoundPlayer();
sound.Stream = ms;
sound.Play();
but I get this exception:
my problem pic http://8pic.ir/images/g699b52xe5ap9s8yf0pz.jpg
The first bytes of a WAV stream contain info about length, etc.
You have to send this "WAV-Header" as well in the first few bytes.
See http://de.wikipedia.org/wiki/RIFF_WAVE
As you'll see its perfectly possible to compose these few bytes in the header and send them before your raw audio data,
You can use some library for reading data from microphone or playing it to speakers.
I worked successfuly with:
NAudio - http://naudio.codeplex.com/
I would not recommend building a WAV file yourself, it may be too much effort for this.
Note that this library (and probably some others, Bass - http://www.un4seen.com is also widely used) also have built in functionality for saving and reading WAV files.
NAudio is best app to play that functionality. use sample app provided.It may help.

NAudio - Changing Bitrate of Recorded WAV file

i am trying to implement audio recording using NAudio to a Wav file, but the default bitrate set by the WasapiLoopbackCapture class can't be changed programmatically.
I am recording the audio output to a MemoryStream (recordedStream in snippet below). However the default bitrate set by the WasapiLoobpackCapture doesn't fit my needs.
I would like to have a bit rate of 320KBPS and i tried to convert the recorded file programmatically using the WaveFormatConversionStream class, but i couldn't make it work.
WaveFormat targetFormat = WaveFormat.CreateCustomFormat(waveIn.WaveFormat.Encoding,
waveIn.WaveFormat.SampleRate, //SampleRate
waveIn.WaveFormat.Channels, //Channels
320000, //Average Bytes per Second
waveIn.WaveFormat.BlockAlign, //Block Align
waveIn.WaveFormat.BitsPerSample); //Bits per Sample
using (WaveStream inputStream = new RawSourceWaveStream(recordedStream, waveIn.WaveFormat))
{
try
{
using (var converter = new WaveFormatConversionStream(targetFormat, inputStream))
{
// ...
}
}
catch (Exception)
{
throw;
}
recordedStream.Dispose();
}
I always get an "AcmNotPossible calling acmStreamOpen" conversion exception. As you see i am using exactly the same format as the recorded WAV file (Extension encoding, 44100 etc.), except the bitrate which is lower in the target waveformat.
What would be the correct codeto do the bitrate conversion from a Wav file contained in a MemoryStream? my goal is to get a 320KBPS file.
For a given sample rate, bit depth, and channel count, PCM audio always has the same bitrate (calculated by multiplying those three values together). If you want to reduce the bitrate, you must change one of those three (lowering the sample rate is probably the best option unless you can go from stereo to mono).
Really you should be thinking of encoding to a format like MP3, WMA or AAC, which will let you select your preferred bitrate.

Using NAudio to play a WAV with custom codec

I have a WAV file that has been recorded using a custom codec. The codec has been installed on my machine, and the WAV file plays fine on my machine using Windows Media player. I am using the NAudio routines to try and play the WAV file via some C# code. The values for the custom format look weird, but I have painstakingly checked them by analysing the WAV file header. Here is the best C# code I have come up with for playing the file:
WaveFormat wfOKI = WaveFormat.CreateCustomFormat(WaveFormatEncoding.DialogicOkiAdpcm, 8000, 1, 3000, 48, 3);
WaveStream wsRaw = new WaveFileReader(txtFileName.Text);
wsRaw = WaveFormatConversionStream.CreatePcmStream(wsRaw); // Line A
wsRaw = new BlockAlignReductionStream(wsRaw); // Line B
WaveStream wsOKI = new RawSourceWaveStream(wsRaw, wfOKI);
WaveOut woCall = new WaveOut();
woCall.Init(wsOKI); // <-- This line gives an error.
woCall.Play();
while (woCall.PlaybackState == PlaybackState.Playing)
{
System.Threading.Thread.Sleep(300);
}
The Init() causes the following error: An unhandled exception of type 'NAudio.MmException' occurred in NAudio.dll. Additional information: WaveBadFormat calling waveOutOpen.
Is the code the correct strategy for playing a WAV with a custom codec? I have tried all four combinations of commenting out/in Lines A and B (with no difference to the error message).
I'm using Windows 7 64-bit, Visual Studio 2010 professional (project is set to x86), and version 1.6 of NAudio. I'm very new to NAudio, but did get a few lines going that played a "standard" WAV (i.e. a file that did not use a custom codec).
If you have got a WAV file then there is no need for the RawSourceWaveStream. You can play the converted stream directly.
var wsRaw = new WaveFileReader(txtFileName.Text);
wsRaw = WaveFormatConversionStream.CreatePcmStream(wsRaw);
WaveOut woCall = new WaveOut();
woCall.Init(wsRaw);
woCall.Play();
Also, you should not be calling thread.sleep to wait for it to finish if you are using WaveOut. Try WaveOutEvent instead if you are not using this from an application with a GUI.

Converting wav file to wav file (changing format)

Trying to find a workaround for my previous question, I'd like to convert a 16k 8bit mono wav which is written in byte[] (which has wav header) to a 8k 8bit mono stream/byte[].
Is there any .Net library with samples available for this kind of conversion?
Thank you.
Thanks for the answers, I ended up using NAudio and with the following snippet, Voila! Everything works like a charm:
WaveFormat target = new WaveFormat(8000, 8 , 1);
WaveStream stream =new WaveFileReader("c:\\test.wav");
WaveFormatConversionStream str = new WaveFormatConversionStream(target, stream);
WaveFileWriter.CreateWaveFile("c:\\converted.wav", str);
Alvas seems to support conversion as well as the usual features:
http://alvas.net/alvas.audio.aspx

Categories