Compress Audio upon writing to file - c#

I am trying to create a recorder from audio coming out from soundcard and this is my progress so far, the problem is the recorded audio when saving to file is so large like a song can reach up to hundreds of megabyte.
here's my code
using NAudio.CoreAudioApi;
using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Record_From_Soundcard
{
public partial class frmMain : Form
{
private WaveFileWriter writer;
private WasapiLoopbackCapture waveInSel;
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
MMDeviceEnumerator deviceEnum = new MMDeviceEnumerator();
MMDeviceCollection deviceCol = deviceEnum.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);
cboAudioDrivers.DataSource = deviceCol.ToList();
}
private void btnStopRecord_Click(object sender, EventArgs e)
{
waveInSel.StopRecording();
writer.Close();
}
private void btnStartRecord_Click(object sender, EventArgs e)
{
using (SaveFileDialog _sfd = new SaveFileDialog())
{
_sfd.Filter = "Mp3 File (*.mp3)|*.mp3";
if (_sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
MMDevice _device = (MMDevice)cboAudioDrivers.SelectedItem;
waveInSel = new WasapiLoopbackCapture(_device);
writer = new WaveFileWriter(_sfd.FileName, waveInSel.WaveFormat);
waveInSel.DataAvailable += (n, m) =>
{
writer.Write(m.Buffer, 0, m.BytesRecorded);
};
waveInSel.StartRecording();
}
}
}
}
}
can anyone help me on how to compress audio upon saving?
maybe it will be added on this part
waveInSel.DataAvailable += (n, m) =>
{
writer.Write(m.Buffer, 0, m.BytesRecorded);
};
Thanks in advance.. ;)

Try this using naudio dll
Using NAudio.Wave; Using NAudio.Wave.SampleProviders;Using NAudio.Lame
Private void WaveToMP3(int bitRate = 128){
String waveFileName = Application.StartupPath + #"\Temporal\mix.wav";
String mp3FileName = Application.StartupPath + #"\Grabaciones\ " + Strings.Format(DateTime.Now, "dd-MM-yyyy.HH.mm.ss") + ".mp3";
Using (var reader = New AudioFileReader(waveFileName))
{
Using (var writer = New LameMP3FileWriter(mp3FileName, reader.WaveFormat, bitRate))
{
reader.CopyTo(writer);
}
reader.Close();
}
}

You can't make an MP3 file by saving a WAV file with a .MP3 extension (which is what you are doing here). You will need to select an encoder available on your machine, and pass the audio through that. I go into some detail about how to do this with NAudio in this article.

Related

RTSP Streaming in Microsoft Dynamics Nav 2016 using Control add In

I am trying to do rtsp streaming in Nav 2016 using control add in using VLC player for dotnet. The control gets added on Nav page but i am not able to stream video from IP camera. The same code works fine on windows application but it does not work in Nav. Here is my sample code. please help me if i am doing anything wrong here.
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Dynamics.Framework.UI.Extensibility;
using Microsoft.Dynamics.Framework.UI.Extensibility.WinForms;
using System.Text.RegularExpressions;
using System.IO.Ports;
using WebEye.Controls.WinForms.StreamPlayerControl;
using Vlc.DotNet.Forms;
namespace WeighControl
{
[ControlAddInExport("CamControl")]
public class CamControl : WinFormsControlAddInBase
{
private VlcControl streamCam1;
private delegate void myDelegate(string str);
[ApplicationVisible]
public event MethodInvoker CamControlAddInReady;
[ApplicationVisible]
public void ShowCameraControl()
{
ShowCamera();
}
public CamControl()
{
}
private void ShowCamera()
{
try
{
streamCam1.Play(new Uri("rtsp://admin:admin#192.168.0.171/"));
}
catch(Exception ex)
{
}
}
protected override Control CreateControl()
{
streamCam1 = new VlcControl();
this.streamCam1.AutoSize = true;
this.streamCam1.BackColor = System.Drawing.Color.Black;
this.streamCam1.Spu = -1;
this.streamCam1.ForeColor = System.Drawing.Color.Black;
this.streamCam1.Location = new System.Drawing.Point(1, 416);
this.streamCam1.Margin = new System.Windows.Forms.Padding(2);
this.streamCam1.Name = "streamCam1";
string path = #"C:\Program Files\VideoLAN\VLC";
System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(path);
this.streamCam1.VlcLibDirectory = directoryInfo;
this.streamCam1.VlcMediaplayerOptions = null;
this.streamCam1.Size = new System.Drawing.Size(540, 226);
this.streamCam1.TabIndex = 2198;
streamCam1.HandleCreated += (sender, args) =>
{
if (CamControlAddInReady != null)
{
CamControlAddInReady();
}
};
return streamCam1;
}
}
}

Access to file denied in C# .NET 3.1 forms

Hello I was writing a basic text editor in C# on visual studio windows form using the .NET framework 3.1 long term support version everything worked fine until I wrote the save file script
Here's the code for "Form1.cs" which is where the open and save file functions reside
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Security.Principal;
namespace Text_Editor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string locsave;
private void openbtn_Click(object sender, EventArgs e)
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
if (principal.IsInRole(WindowsBuiltInRole.Administrator) != true)
{
MessageBox.Show("Run as Admin");
System.Windows.Forms.Application.ExitThread();
}
else
{
OpenFileDialog openfile = new OpenFileDialog();
if (openfile.ShowDialog() == DialogResult.OK)
{
var locationArray = openfile.FileName;
string location = "";
locsave = locationArray;
foreach (char peice in locationArray)
{
location = location + peice;
}
var contentArray = File.ReadAllText(location);
string content = "";
label4.Text = location;
foreach (char peice in contentArray)
{
content = content + peice;
}
richTextBox1.Text = content;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine("Test");
}
private void savebtn_Click(object sender, EventArgs e)
{
if (#label4.Text == "")
{
MessageBox.Show("Open a text file first");
}
else
{
StreamWriter outputfile = new StreamWriter(locsave);
outputfile.Write(richTextBox1.Text); //this is where the error occures and it throws the error of access denyed
outputfile.Close();
}
}
}
}
Does anyone have a suggestion about what to do I looked around on google for a solution but it seemed most did not work and some others I did not understand.

Vlc.dotnet.form pause video with a button

I am hoping someone can help me in getting an issue of mine to work, I feel as if it is an easy one, however not having any luck in fixing what I am trying to do. I want to be able to pause a video which I am playing using vlc.dotnet below is a brief summary of the structure of my code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;
using Vlc.DotNet.Forms;
using System.Threading;
using Vlc.DotNet.Core;
using System.Diagnostics;
namespace TS1_C
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
button8.Click += new EventHandler(this.button8_Click);
}
void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
string chosen = listBox1.SelectedItem.ToString();
string final = selectedpath2 + "\\" + chosen; //Path
playfile(final);
}
void playfile(string final)
{
var control = new VlcControl();
var currentAssembly = Assembly.GetEntryAssembly();
var currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName;
// Default installation path of VideoLAN.LibVLC.Windows
var libDirectory = new DirectoryInfo(Path.Combine(currentDirectory, "libvlc", IntPtr.Size == 4 ? "win-x86" : "win-x64"));
control.BeginInit();
control.VlcLibDirectory = libDirectory;
control.Dock = DockStyle.Fill;
control.EndInit();
panel1.Controls.Add(control);
control.Play();
}
private void button8_Click(object sender, EventArgs e)
{
}
}
}
As you can see I have one method which takes a double click from an item in a list box and plays it using the method playfile. However I want to be able to pause the video using my button known as button8. I have tried many things even this
control.Paused += new System.EventHandler<VlcMediaPlayerPausedEventArgs>(button8_Click);
Which I put into the playfile method, however nothing seems to work. I am wondering if my whole method in which I play a file using playfile(); is completely wrong. I am hoping someone can help me in trying to achieve what I need
Thank you
Your control should be initialized only once:
private VlcControl control;
public Form1()
{
InitializeComponent();
control = new VlcControl();
var currentAssembly = Assembly.GetEntryAssembly();
var currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName;
// Default installation path of VideoLAN.LibVLC.Windows
var libDirectory = new DirectoryInfo(Path.Combine(currentDirectory, "libvlc", IntPtr.Size == 4 ? "win-x86" : "win-x64"));
control.BeginInit();
control.VlcLibDirectory = libDirectory;
control.Dock = DockStyle.Fill;
control.EndInit();
panel1.Controls.Add(control);
}
then, your play method could be simplified:
void playfile(string url)
{
control.Play(url);
}
And for your pause method:
private void button8_Click(object sender, EventArgs e)
{
control.Pause();
}

ArgumentException "parameter is incorrect"

I'm trying to make a code that converts memorystream to a png image, but I'm getting a ArgumentException "parameter is incorrect" error on using(Image img = Image.FromStream(ms)). It doesn't specify it any further so I don't know why I'm getting the error and what am I supposed to do to it.
Also, how do I use the Width parameter with img.Save(filename + ".png", ImageFormat.Png);? I know I can add parameters and it recognizes "Width", but I have no idea how it should be formatted so visual studio would accept it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
MemoryStream ms = new MemoryStream();
public string filename;
private void button1_Click(object sender, EventArgs e)
{
OpenFile();
}
private void button2_Click(object sender, EventArgs e)
{
ConvertFile();
}
private void OpenFile()
{
OpenFileDialog d = new OpenFileDialog();
if(d.ShowDialog() == DialogResult.OK)
{
filename = d.FileName;
var fs = d.OpenFile();
fs.CopyTo(ms);
}
}
private void ConvertFile()
{
using(Image img = Image.FromStream(ms))
{
img.Save(filename + ".png", ImageFormat.Png);
}
}
}
}
I suspect the problem is with how you're reading the file here:
fs.CopyTo(ms);
You're copying the content of the file into the MemoryStream, but then leaving the MemoryStream positioned at the end of the data rather than the start. You can fix that by adding:
// "Rewind" the memory stream after copying data into it, so it's ready to read.
ms.Position = 0;
You should consider what happens if you click on the buttons multiple times though... and I'd strongly advise you to use a using directive for your FileStream, as currently you're leaving it open.

Need to zip text files from a predefined location & save the zipped files in another location of hard disk using windows services

Need to zip text files from a predefined location & save the zipped files in another location of hard disk using windows services & delete the old text file (a scheduled service)
I tried the following code in which i used 'icsharpcode' for zipping the files. But after installing the service.. i am getting a message that "this services has started & then stopped..." without showing any required output.
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.Design;
using System.Diagnostics.Eventing;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Timers;
using ICSharpCode.SharpZipLib.Zip;
namespace createzip
{
public partial class createzip : ServiceBase
{
Timer timer1 = new Timer();
public createzip()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer1.Elapsed += new ElapsedEventHandler(onelapsedtime);
timer1.Enabled = true;
timer1.Interval = 60000;
}
protected override void OnStop()
{
timer1.Enabled = false;
}
private void onelapsedtime(object source, ElapsedEventArgs e)
{
string folder = "#E:\\zipped files";
Directory.SetCurrentDirectory(folder);
string output = "#E:\\output";
string outputfilename = Path.Combine(output, "this file is zipped");
using (var x = new ZipFile(output))
{
foreach (var f in Directory.GetFiles(folder))
x.Add(f);
}
string[] filenames = Directory.GetFiles(folder);
using ( ZipOutputStream s = new
ZipOutputStream(File.Create(output))) //(args[1])))
{
s.SetLevel(9);
byte[] buffer = new byte[4096];
foreach (string file in filenames)
{
ZipEntry entry = new ZipEntry(Path.GetDirectoryName(file));
//entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
int sourcebytes;
do
{
sourcebytes = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, sourcebytes);
}
while (sourcebytes > 0);
}
}
s.Finish();
s.Close();
return;
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Timers;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
namespace trail2zip
{
public partial class trail2zip : ServiceBase
{
Timer timer;
string path1 = #"E:\zipped files\New Text Document.txt";
string path2 = #"E:\output\filezipname.zip";
string path3 = #"E:\zipped files\R_23122015.txt";
int timerInterval = 60000;
public trail2zip()
{
InitializeComponent();
timer = new Timer();
timer.Elapsed+=new ElapsedEventHandler(this.timer_Elapsed);
timer.Interval = timerInterval;
timer.Enabled = true;
}
protected override void OnStart(string[] args)
{
timer.Start();
}
protected override void OnStop()
{
timer.Stop();
timer.SynchronizingObject = null;
timer.Elapsed -= new ElapsedEventHandler(this.timer_Elapsed);
timer.Dispose();
timer = null;
}
public void timer_Elapsed(object sender, ElapsedEventArgs e)
{
ZipFile z = ZipFile.Create(path2); //(filezipname);
z.BeginUpdate();
z.Add(path1);
z.Add(path3);
z.CommitUpdate();
z.Close();
}
}
}

Categories

Resources