How to use accord for low pass filter c# .net - accord.net

I have generated a sin wave 4KHz .wav file using NAudio library now I am trying to pass it through a Low Pass Filter using Accord.Audio.Filters LPF implementation.
I am getting the resulting wav file but still the sin wave signal is present after passing through LPF only difference is the volume/gain or amplitude is less when I play the output wav file.
Below is my implementation
is there anything wrong in the code?
var inSignal = Signal.FromFile("filteroutput.wav");
LowPassFilter accordFilter = new LowPassFilter(1, inSignal.SampleRate);
var outSignal = accordFilter.Apply(inSignal);
MemoryStream destinationStream = new MemoryStream();
//var fileStream = new FileStream("filteroutput1.wav", FileMode.CreateNew, FileAccess.ReadWrite);
// Create a encoder for the destination stream
WaveEncoder encoder = new WaveEncoder("filteroutput1.wav");
// Encode the signal to the destination stream
encoder.Encode(outSignal);

Related

.NET Core API saving image upload asynchronously with ImageSharp, MemoryStream and FileStream

I have a .NET Core API that I'd like to extend to save uploaded images asynchronously.
Using ImageSharp I should be able to check uploads and resize if predefined size limits are exceeded. However I can't get a simple async save working.
A simple (non-async) save to file works without problem:
My Controller extracts IFormFile from the upload and calls the following method without any problem
public static void Save(IFormFile image, string imagesFolder)
{
var fileName = Path.Combine(imagesFolder, image.FileName);
using (var stream = image.OpenReadStream())
using (var imgIS = Image.Load(stream, out IImageFormat format))
{
imgIS.Save(fileName);
}
}
ImageSharp is currently lacking async methods so a workaround is necessary.
The updated code below saves the uploaded file but the format is incorrect - when viewing the file I get the message "It appears we don't support this file format".
The format is extracted from the ImageSharp Load method. and used when saving to MemoryStream.
MemoryStream CopyToAsync method is used to save to FileStream to make the upload asynchronous.
public static async void Save(IFormFile image, string imagesFolder)
{
var fileName = Path.Combine(imagesFolder, image.FileName);
using (var stream = image.OpenReadStream())
using (var imgIS = Image.Load(stream, out IImageFormat format))
using (var memoryStream = new MemoryStream())
using (var fileStream = new FileStream(fileName, FileMode.OpenOrCreate))
{
imgIS.Save(memoryStream, format);
await memoryStream.CopyToAsync(fileStream).ConfigureAwait(false);
fileStream.Flush();
memoryStream.Close();
fileStream.Close();
}
}
I can't work out whether the issue is with ImageSharp Save to MemoryStream, or the MemoryStream.CopyToAsync.
I'm currently getting 404 on SixLabors docs - hopefully not an indication that the project has folded.
How can I make the upload async and save to file in the correct format?
CopyToAsync copies a stream starting at its current position. You must change the current position of memoryStream back to start before copying:
// ...
memoryStream.Seek(0, SeekOrigin.Begin);
await memoryStream.CopyToAsync(fileStream).ConfigureAwait(false);
// ...

iTextSharp v5 - How do you concatenate PDFs in memory?

I am having trouble merging PDFs in-memory. I have 2 memory streams, a master and component stream, the idea is that as each component PDF is built up, the component PDF's bytes are added to the master stream. At the very end of all the components, we have a byte array that's a PDF.
I have the code below, but nothing is copying into my masterStream. I think the issue is with CopyPagesTo, but I'm not familiar enough and the documentation/examples are hard to find.
byte[] updated;
using (MemoryStream masterMemoryStream = new MemoryStream())
{
masterStream.WriteTo(masterMemoryStream);
// Read from master stream (ie. all existing components)
masterMemoryStream.Position = 0;
using (iText.Kernel.Pdf.PdfWriter masterPdfWriter = new iText.Kernel.Pdf.PdfWriter(masterMemoryStream))
using (iText.Kernel.Pdf.PdfDocument masterPdfDocument = new iText.Kernel.Pdf.PdfDocument(masterPdfWriter))
{
using (MemoryStream componentMemoryStream = new MemoryStream())
{
componentStream.WriteTo(componentMemoryStream);
// Read from new component
componentMemoryStream.Position = 0;
using (iText.Kernel.Pdf.PdfReader componentPdfReader = new iText.Kernel.Pdf.PdfReader(componentMemoryStream))
using (iText.Kernel.Pdf.PdfDocument componentPdfDocument = new iText.Kernel.Pdf.PdfDocument(componentPdfReader))
{
// Copy pages from component into master
componentPdfDocument.CopyPagesTo(1, componentPdfDocument.GetNumberOfPages(), masterPdfDocument);
}
}
}
updated = masterMemoryStream.GetBuffer();
}
// Write updates to master stream?
masterStream.SetLength(0);
using (MemoryStream temp = new MemoryStream(updated))
temp.WriteTo(masterStream);
Answer
This is mkl's answer with some of my corrections:
using (MemoryStream temporaryStream = new MemoryStream())
{
masterStream.Position = 0;
componentStream.Position = 0;
using (PdfDocument combinedDocument = new PdfDocument(new PdfReader(masterStream), new PdfWriter(temporaryStream)))
using (PdfDocument componentDocument = new PdfDocument(new PdfReader(componentStream)))
{
componentDocument.CopyPagesTo(1, componentDocument.GetNumberOfPages(), combinedDocument);
}
byte[] temporaryBytes = temporaryStream.ToArray();
masterStream.Position = 0;
masterStream.SetLength(temporaryBytes.Length);
masterStream.Capacity = temporaryBytes.Length;
masterStream.Write(temporaryBytes, 0, temporaryBytes.Length);
}
There are a number of issues in your code. I'll first give you a working version and then go into the issues in your code.
A working version (with an important limitation)
You can combine two PDFs given in MemoryStream instances masterStream and componentStream and get the result in the same MemoryStream instance masterStream as follows:
using (MemoryStream temporaryStream = new MemoryStream())
{
masterStream.Position = 0;
componentStream.Position = 0;
using (PdfDocument combinedDocument = new PdfDocument(new PdfReader(masterStream), new PdfWriter(temporaryStream)))
using (PdfDocument componentDocument = new PdfDocument(new PdfReader(componentStream)))
{
componentDocument.CopyPagesTo(1, componentDocument.GetNumberOfPages(), combinedDocument);
}
byte[] temporaryBytes = temporaryStream.ToArray();
masterStream.Position = 0;
masterStream.Capacity = temporaryBytes.Length;
masterStream.Write(temporaryBytes, 0, temporaryBytes.Length);
masterStream.Position = 0;
}
The limitation is that you have to have instantiated the masterStream with an expandable capacity; the MemoryStream class has a number of constructors only some of which create such an expandable instance while the others create non-resizable instances. For details read here.
Issues in your concept and code
Concatenating PDF files does not result in a valid merged PDF
You describe your concept like this
the idea is that as each component PDF is built up, the component PDF's bytes are added to the master stream
This does not work, though, the PDF format does not allow merging PDFs by simply concatenating them. In particular the (active) objects in a PDF have an identifier number which must be unique in the PDF, concatenating would result in a file with non-unique object identifiers; PDFs contain cross reference structures which map each object identifier to its offset from the file start, concatenating would get all these offsets wrong for the added PDFs; furthermore, a PDF has to have a single root object from which the other objects are referenced directly or indirectly, concatenating would result in multiple root objects.
Writing and immediately overwriting
In your code you have
masterStream.WriteTo(masterMemoryStream);
// Read from master stream (ie. all existing components)
masterMemoryStream.Position = 0;
using (iText.Kernel.Pdf.PdfWriter masterPdfWriter = new iText.Kernel.Pdf.PdfWriter(masterMemoryStream))
Here you write the contents of masterStream to masterMemoryStream, then set the masterMemoryStream position to the start and instantiate a PdfWriter which starts writing there. I.e. your original copy of the masterStream contents get overwritten, surely not what you wanted.
Using MemoryStream.GetBuffer
MemoryStream.GetBuffer does not only return the data written into the MemoryStream by design but the whole buffer; i.e. there may be a lot of trash bytes after the actual PDF in what you retrieve here
updated = masterMemoryStream.GetBuffer();
This may cause PDF processors trying to process your result PDFs to be unable to open the file: PDFs have a pointer to the last cross references at their end, so if you have trash bytes following the actual end of your PDF, PDF processors may not find that pointer.
PS
As worked out in the comments, the code above works fine in case of constantly growing stream lengths (which usually will happen in the use case at hand) but in general one needs to restrict the stream size before writing the new content, e.g. like this:
...
masterStream.Position = 0;
masterStream.SetLength(temporaryBytes.Length); // <<<<
masterStream.Capacity = temporaryBytes.Length;
...

Create WAV stream in memory

I have a URL to MP4 audio file that I need to send to Speech-To-Text API. The API accepts only WAV stream. I am using NAudio 1.7.3 and the following code to download the file and to get the appropriate stream to be sent to API:
string filePath = "C:\Windows\Temp\file.wav";
using (MediaFoundationReader reader = new MediaFoundationReader(audioFileURL))
{
WaveFileWriter.CreateWaveFile(filePath, reader);
}
System.IO.FileStream fs = new FileStream(filePath, FileMode.Open);
Then I send the fs stream to API and everything works correctly, although very slowly because of I/O to/from disk.
I decided to rewrite this code and execute all required in memory. For this purpose I wrote the following code (that does not provide me a correct stream):
using (MediaFoundationReader reader = new MediaFoundationReader(audioLocation)){
MemoryStream ms = new MemoryStream();
IgnoreDisposeStream ids = new IgnoreDisposeStream(ms);
WaveFileWriter writer = new WaveFileWriter(ids, reader.WaveFormat);
//Doing one of the following (both provide the same outcome):
//1. reader.CopyTo(ids);
//or
//2. this code from NAudio source:
var buffer = new byte[reader.WaveFormat.AverageBytesPerSecond * 4];
while (true)
{
int bytesRead = reader.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
// end of source provider
break;
}
// Write will throw exception if WAV file becomes too large
writer.Write(buffer, 0, bytesRead);
}
writer.Dispose();
Stream streamToSendToAPI = ids.SourceStream;
//Send streamToSendToAPI to Speech-To-Text API
}
My expectation is that using second code example, where I create stream with WAV header and then add the data to the stream, would provide me a valid WAV stream. However, when I send it to speech-to-text API, the API gives error that indicates that stream cannot be processed (meaning that stream is invalid).
Please advise how to fix the in-memory code example to create a valid WAV stream
You need to rewind the memory stream back to the beginning
ms.Position = 0

Windows Store 8.1: WebView.NavigateToStream does not work when altering stream

I am currently trying to use the WebView to display encrypted data (using DPP). The issue is that I am not able to get the WebView to show anything if the stream is manipulated in any way after reading the StorageFile into an IRandomAccessStream (ie. unencrypt the data).
This issue can easily be reproduced by using the source provided by Microsoft: http://code.msdn.microsoft.com/windowsapps/XAML-WebView-control-sample-58ad63f7
and altering the "StreamUriWinRTResolver" class to convert the IRandomAccessStream to a memory stream and then back again. Basically, in S4_NavToStream.xaml.cs at line 128, change this:
StorageFile f = item as StorageFile;
IRandomAccessStream stream = await f.OpenAsync(FileAccessMode.Read);
return stream.GetInputStreamAt(0);
With this:
StorageFile f = item as StorageFile;
IRandomAccessStream randStream = await f.OpenAsync(FileAccessMode.Read);
var stream = randStream.AsStream();
MemoryStream ms = new MemoryStream();
stream.CopyTo(ms);
return ms.AsInputStream();
This will show a blank page when run. I'm starting to think this is a bug, unless of course I'm using the stream conversions incorrectly. Has anybody tried anything similar?
Thomas Huber has very graciously answered my question over on social.msdn.microsoft.com. Full answer here:
http://social.msdn.microsoft.com/Forums/en-US/f51ab699-66c3-4961-8952-fbe341bf3e23/windows-81-webviewnavigatetostream-does-not-work-when-altering-the-stream
In summary, the issue is around the conversion of the memory stream to an input stream. This is the correct working code:
StorageFile f = item as StorageFile;
IRandomAccessStream randStream = await f.OpenAsync(FileAccessMode.Read);
var stream = randStream.AsStream();
var ms = new MemoryStream();
stream.CopyTo(ms);
InMemoryRandomAccessStream msras = new InMemoryRandomAccessStream();
DataWriter dw = new DataWriter(msras);
dw.WriteBytes(ms.ToArray());
await dw.StoreAsync();
var inputStream= msras.GetInputStreamAt(0);
return inputStream;

How to send canvas image large size from silverlight to WCF service

I have a large size byte[] formed from silverlight Canvas using following code
var img = new WriteableBitmap(cnvControlHolder, null);
var outStream = new MemoryStream();
EncodeJpeg(img, outStream);
Now I want to send this to WCF service to form image from this byte array & save it as an image on server side so that I can consume it in SSRS. My problem is as the byte[] is big I get the classic Method not found from WCF service.
I read in few links that WCF streaming would be one option, but could not find any sample on the net. My service method is like this:
public bool Upload(Stream image)
{
FileStream fileStream = null;
BinaryWriter writer = null;
var filePath = HttpContext.Current.Server.MapPath(".") + #"\" +
ConfigurationManager.AppSettings["PictureUploadDirectory"] + #"\Diagram.jpeg";// +image.ImageName;
if (image!=null)
{
//return ByteArrayToFile(filePath, image.Imagestream);
fileStream = File.Open(filePath, FileMode.Create);
writer = new BinaryWriter(fileStream);
writer.Write("Diagram.jpeg");
}
return false;
}
and client call is this :
var img = new WriteableBitmap(canvas1, null);
var outStream = new MemoryStream();
EncodeJpeg(img, outStream); //custom library to compress into jpeg
var client = new Service1Client();
client.UploadCompleted += new EventHandler<UploadCompletedEventArgs>(client_UploadCompleted);
client.UploadAsync(outStream.ToArray());
Can somebody suggest some sample or any other solution to fix my issue.
I recently implemented a very similar solution in Silverlight. The solution involves:
Dividing the large byte[] into n chunks of size that can be sent via a web service call
Making a web call to the service, registering a file upload request for n chunks, and requesting a guid from the service.
Making n web calls to the service and uploading each chunk, supplying the guid and the ordinal of the chunk (the chunks may arrive out of sequence).
Once the server receives all n chunks, it combines the chunks and writes the data into a file.
I hope this can help to get you started.