NAudio.UWP Record ,Write .wav - audio

I know that NAudio.UWP is a work in progress but the newest release (1.8) does seem to have the ability to write a .wav.
private IWavePlayer player;
private WaveStream reader;
private IWaveIn recorder;
private MemoryStream recordStream;
private IRandomAccessStream selectedStream;
private void Record()
{
if (recorder == null)
{
recorder = new WasapiCaptureRT();
recorder.RecordingStopped += RecorderOnRecordingStopped;
recorder.DataAvailable += RecorderOnDataAvailable;
}
if (reader != null)
{
reader.Dispose();
reader = null;
}
recorder.StartRecording();
}
private async void RecorderOnDataAvailable(object sender, WaveInEventArgs waveInEventArgs)
{
Debug.WriteLine(waveInEventArgs.BytesRecorded);
if (reader == null)
{
recordStream = new MemoryStream();
reader = new RawSourceWaveStream(recordStream, recorder.WaveFormat);
}
await recordStream.WriteAsync(waveInEventArgs.Buffer, 0, waveInEventArgs.BytesRecorded);
}
Where/How do you create the Storage file name, path etc? There is no destination param...This is the only code that came with the example.
**Mark if you see this Chrome is blocking the 1.8 code download.

Where/How do you create the Storage file name, path etc?
It actually depends on your requirements. For example, you could use fixed name and timestamp to named your audio file.
var file = KnownFolders.MusicLibrary.CreateFileAsync("song"+DateTime.Now.ToString("yyyy-MM-DD-hh-mm-ss")+".wav",CreationCollisionOption.GenerateUniqueName);

You could copy record stream to a new file stream. For example:
var file = await KnownFolders.MusicLibrary.CreateFileAsync("test.wav");
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
recordStream.CopyTo(stream.AsStream());
}

Related

Excel File Upload with Kendo UI

while I was trying to upload an excel file with kendo ui I found a code on the internet. It is using a keyword named "Constants" but this keyword does not recognize the ".xls" file extension. I am stuck at this and did some research but have no answer to solve this. Here is my code:
public ActionResult Submit(IEnumerable<HttpPostedFileBase> files)
{
if(files!= null)
{
string fileName;
string filePath;
string fileExtension;
foreach(var f in files)
{
//Set file details
SetFileDetails(f, out fileName, out filePath, out fileExtension);
if(fileExtension == Constants.xls || fileExtension == Constants.xlsx)
{
//Save the uploaded file to app folder
string savedExcelFiles = Constants.UploadedFolder + fileName;
f.SaveAs(Server.MapPath(savedExcelFiles));
ReadDataFromExcelFiles(savedExcelFiles);
}
else
{
//file not supported send alert
}
}
}
return RedirectToActionPermanent("Index","Connect");
}
private static void SetFileDetails(HttpPostedFileBase f,out string fileName,out string filePath,out string fileExtension)
{
fileName=Path.GetFileName(f.FileName);
fileExtension=Path.GetExtension(f.FileName);
filePath = Path.GetFullPath(f.FileName);
}
private void ReadDataFromExcelFiles(string savedExcelFiles)
{
var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;",Server.MapPath(savedExcelFiles));
//fill the DataSet by the sheets
var adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]",connectionString);
var ds = new DataSet();
List<UploadExcel> uploadExl = new List<UploadExcel>();
adapter.Fill(ds,"Subscriber");
DataTable data=ds.Tables["Subscriber"];
GetSetUploadExcelData(uploadExl,data);
}
private static void GetSetUploadExcelData (List<UploadExcel> uploadExl,DataTable data)
{
for(int i=0;i<data.Rows.Count-1;i++)
{
UploadExcel NewUpload = new UploadExcel();
NewUpload.ID = Convert.ToInt16(data.Rows[i]["ID"]);
NewUpload.CostCenter = Convert.ToString(data.Rows[i]["CostCenter"]);
NewUpload.FirstName = Convert.ToString(data.Rows[i]["FirstName"]);
NewUpload.LastName = Convert.ToString(data.Rows[i]["LastName"]);
NewUpload.MobileNo = Convert.ToString(data.Rows[i]["MobileNo"]);
NewUpload.EmailID = Convert.ToString(data.Rows[i]["EmailID"]);
NewUpload.Services = Convert.ToString(data.Rows[i]["Services"]);
NewUpload.UsageType = Convert.ToString(data.Rows[i]["UsageType"]);
NewUpload.Network = Convert.ToString(data.Rows[i]["Network"]);
NewUpload.UsageIncluded = Convert.ToInt16(data.Rows[i]["UsageIncluded"]);
NewUpload.Unit = Convert.ToString(data.Rows[i]["Unit"]);
uploadExl.Add(NewUpload);
}
}
}
I suspect that the Constants.xls relates to a static class or enum that the original code author is using to hold the .xls/.xlsx extensions.
If you create a constants class something like:
public static class Constants
{
public static string xls = "xls";
public static string xlsx = "xlsx";
}
This would then should help.
If you need any more assistance then please let me know.
edit: Just reviewing the code it seems they are also putting in constant mapping for the uploadfolder location as well so I suspect this is just a static class rather than an enum with application specific details. in a way a bit like using the appSettings within webconfig

How to hide the cursor in Awesomium

I tried this:
<awe:WebControl x:Name="webBrowser" Cursor="None" Source="http://example.com/"/>
but the cursor still shows.
I figured that I could alter the CSS of the page by adding the following line:
*{
cursor: none;
}
But, is there a solution for when I don't have the access to the actual page that I'm showing?
You can use a ResouceInterceptor and manipulate the page on the fly to insert custom CSS.
EDIT:
The following implementation should do the job. (It assumes there is a text.css file)
class ManipulatingResourceInterceptor : IResourceInterceptor
{
public ResourceResponse OnRequest(ResourceRequest request)
{
Stream stream = null;
//do stream manipulation
if (request.Url.ToString() == "http://your.web.url/test.css")
{
WebRequest myRequest;
myRequest = WebRequest.Create(request.Url);
Stream webStream = myRequest.GetResponse().GetResponseStream();
StreamReader webStreamReader = new StreamReader(webStream);
string webStreamContent = webStreamReader.ReadToEnd();
stream = webStream;
string extraContent = "*{cursor: none;}";
webStreamContent += extraContent;
byte[] responseBuffer = Encoding.UTF8.GetBytes(webStreamContent);
// Initialize unmanaged memory to hold the array.
int responseSize = Marshal.SizeOf(responseBuffer[0]) * responseBuffer.Length;
IntPtr pointer = Marshal.AllocHGlobal(responseSize);
try
{
// Copy the array to unmanaged memory.
Marshal.Copy(responseBuffer, 0, pointer, responseBuffer.Length);
return ResourceResponse.Create((uint)responseBuffer.Length, pointer, "text/css");
}
finally
{
// Data is not owned by the ResourceResponse. A copy is made
// of the supplied buffer. We can safely free the unmanaged memory.
Marshal.FreeHGlobal(pointer);
stream.Close();
}
}
return null;
}
public bool OnFilterNavigation(NavigationRequest request)
{
return false;
}
}

Writing a decompression mechanism to be used in a Web API MessageHandler

I'm trying to write a decompression mechanism for a Web API MessageHandler. However, despite a little research I can't seem to make this work :-(
The problem is reproducible with the following test:
[Test]
public void Deflate()
{
using (var outStream = new MemoryStream())
{
using (var compressionStream = new DeflateStream(outStream, CompressionMode.Compress, true))
{
using (var original = new MemoryStream(Encoding.UTF8.GetBytes("original content")))
{
original.CopyTo(compressionStream);
}
}
//this passes
Assert.IsTrue(outStream.Length > 0);
var compressedStream = outStream;
var decompressionResultStream = compressedStream.DeflateDecompressor();
//this fails
Assert.IsTrue(decompressionResultStream.Length > 0);
var output = Encoding.UTF8.GetString(decompressionResultStream.ToArray());
Assert.AreEqual("original content", output);
}
}
and the following Decompression Handler
public static class DecompressionHandlers
{
public static MemoryStream DeflateDecompressor(this Stream compressedStream)
{
var decompressionResultStream = new MemoryStream();
using (var decompressionStream = new DeflateStream(compressedStream, CompressionMode.Decompress, true))
{
decompressionStream.CopyTo(decompressionResultStream);
decompressionStream.Flush();
}
return decompressionResultStream;
}
public static MemoryStream GZipDecompressor(this Stream compressedStream)
{
var decompressionResultStream = new MemoryStream();
using (var decompressionStream = new GzipStream(compressedStream, CompressionMode.Decompress, true))
{
decompressionStream.CopyTo(decompressionResultStream);
decompressionStream.Flush();
}
return decompressionResultStream;
}
}
Hopefully, this is a straight ID-ten-T problem and any advice is gratefully received!
That this is to be used in a Web API MessageHandler may well be a red herring but is included for completeness
In your code, try resetting the position of the compressedStream before you invoke decompression on it.
compressedStream.Position = 0;
var decompressionResultStream = compressedStream.DeflateDecompressor();
Note that you seem to be using DeflateStream instead of GZipStream in your GZipDecompressor method.

codenameone - Storage file doesn't delete

I've added storage file to my codenameone application. In some event I wanna delete specific storage file and recreate it with some old filtered data and new data. It doesn't work well on deletion.
First I create method for clear storage file in StorageManager class:
public void clearData(String pStorageTable){
Storage.getInstance().deleteStorageFile(pStorageTable);
}
In other class I use this method like this:
// load all data of specific storage file
// ...
new DBManager().clearData(ThreeTrans.DB_NAME);
// write old data with filtering of specific ID and new data
// ...
here is method of write data:
public void write(ThreeTrans pTT){
if(store == null) {
store = Storage.getInstance();
}
DB_NAME = "TT";
if(!store.exists(DB_NAME)) {
Hashtable depHash = new Hashtable();
String k = "1" + pTT.getNumber();
depHash.put(k, pTT.toString());
store.writeObject(DB_NAME, depHash);
}
else {
Hashtable depHash = (Hashtable)store.readObject(DB_NAME);
if (!depHash.containsValue(pTT.getNumber())) {
String k = String.valueOf(getLastKeyNumber());
depHash.put(k, pTT.toString());
store.writeObject(DB_NAME, depHash);
}
}
}
at first I was using this method for delete storage file:
public void clearData(String pStorageTable){
if(store == null) {
store = Storage.getInstance();
}
for (String str : store.listEntries()) {
if(str.toLowerCase().startsWith(pStorageTable)) {
store.deleteStorageFile(str);
}
}
}
and after this problem this method changed to this;
public void clearData(String pStorageTable){
Storage.getInstance().deleteStorageFile(pStorageTable);
}
I'm assuming that you didn't invoke close() on the output stream or the input stream working with the file and there is still a lock on the file. This is usually the case for such issues.

Merge memorystreams to one iText document

I have four MemoryStreams of data that I want to merge and then open the pdfDocument, without creating a single file.
It's possible to write them down to files and then merge them but that would be bad practice and that can also cause a few issues so I want to avoid that.
However, I can not find a way to merge the MemoryStreams with iText5 for .NET.
Right now, this is how I do it with files:
private static void ConcatenateDocuments()
{
var stream = new MemoryStream();
var readerFrontPage = new PdfReader(Folder + FrontPageName);
var readerDocA = new PdfReader(Folder + docA);
var readerDocB = new PdfReader(Folder + DocB);
var readerAppendix = new PdfReader(Folder + Appendix);
var pdfCopyFields = new PdfCopyFields(stream);
pdfCopyFields.AddDocument(readerFrontPage);
pdfCopyFields.AddDocument(readerDocA );
pdfCopyFields.AddDocument(readerDocB);
pdfCopyFields.AddDocument(readerAppendix);
pdfCopyFields.Close();
SavePdf(stream, FilenameReport);
}
Since I need to remove the use of files, I keep the MemoryStream's as the different parts are built from different resources. So I have references to these memorystreams.
How can this be done?
The error PDF header signature not found can be fixed in this case by setting the stream's Position back to 0. Since you're not getting the error Cannot access a closed Stream I'm assuming that you are already correctly setting the PdfWriter's CloseStream to false.
Below is a full working C# 2010 WinForm app targeting iTextSharp 5.1.1.0 that creates three PDFs in MemoryStreams and combines them. Since I don't have a web server handy I'm writing them to disk.
using System;
using System.Text;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Create three MemoryStreams
MemoryStream[] streams = { CreateDoc("Page 1"), CreateDoc("Page 2"), CreateDoc("Page 3") };
//I don't have a web server handy so I'm going to write my final MemoryStream to a byte array and then to disk
byte[] bytes;
//Create our final combined MemoryStream
using (MemoryStream finalStream = new MemoryStream())
{
//Create our copy object
PdfCopyFields copy = new PdfCopyFields(finalStream);
//Loop through each MemoryStream
foreach (MemoryStream ms in streams)
{
//Reset the position back to zero
ms.Position = 0;
//Add it to the copy object
copy.AddDocument(new PdfReader(ms));
//Clean up
ms.Dispose();
}
//Close the copy object
copy.Close();
//Get the raw bytes to save to disk
bytes = finalStream.ToArray();
}
//Write out the file to the desktop
string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Combined.pdf");
using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
fs.Write(bytes, 0, bytes.Length);
}
this.Close();
}
/// <summary>
/// Helper method to create temporary documents
/// </summary>
private MemoryStream CreateDoc(string name)
{
MemoryStream ms = new MemoryStream();
using (Document doc = new Document(PageSize.LETTER))
{
using (PdfWriter writer = PdfWriter.GetInstance(doc, ms))
{
writer.CloseStream = false;
doc.Open();
doc.Add(new Paragraph(name));
doc.Close();
}
}
return ms;
}
}
}
While it seams the PdfReader can not take the stream, the array of the stream works.
var readerFrontPage = new PdfReader(streamFrontPage.ToArray());

Resources