saving .wav files without showdialog in C# - c#

Problem: I don't want the user to decide which location the recorded WAV file should be saved,the wav file should save in c:\ . for example when button 2 is clicked the wav file saves to "c:\". I hope you guys can help me.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
//voice recorder
namespace recorder
{
public partial class Form1 : Form
{
[DllImport("winmm.dll")]
private static extern int mciSendString(string MciComando, string MciRetorno, int MciRetornoLeng, int CallBack);
string musica = "";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
label1.Visible = false; //label1.Text=recording
}
//starts recording what I say to mic
private void btnStart_Click(object sender, EventArgs e)
{
label1.Visible = true;
mciSendString("open new type waveaudio alias Som", null, 0, 0);
mciSendString("record Som", null, 0, 0);
}
//stops recording and shows a save form
//This is where the problem is.
/* I don't want the program to ask the user for location and file name and format to be
saved as. I just want the file to save in c:\ with the filename "recording1" with format
as .wav */
private void btnStopnSave_Click(object sender, EventArgs e)
{
label1.Visible = false;
mciSendString("pause Som", null, 0, 0);
SaveFileDialog save = new SaveFileDialog();
save.Filter = "WAVE|*.wav";
if (save.ShowDialog() == DialogResult.OK) // this is where it needs to be altered
{
mciSendString("save Som " + save.FileName,null,0, 0);
mciSendString("close Som", null, 0, 0);
}
}
//lets user to open a WAV file by browsing files
private void btnPlay_Click(object sender, EventArgs e)
{
if (musica == "")
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Wave|*.wav";
if (open.ShowDialog() == DialogResult.OK) { musica = open.FileName; }
}
mciSendString("play " + musica, null, 0, 0);
}
}
}

Just don't show the Dialog and put a constant string instead of using the instance of class SaveFileDialog.
var fileName = "C:/mySound.wav";
mciSendString("save Som " + fileName,null,0, 0);
mciSendString("close Som", null, 0, 0);

Try this:
private void StopRecordingAndSave(string OutputFolerPath, string OutputFileName)
{
mciSendString(#"save recsound" + OutputFolderPath + OutputFileName + ".wav","",0,0);
mciSendString(#"close recsound ","", 0,0);
}

Related

Cursor Application Issues

So I'm trying to create an application that displays all the cursors in the folder C:\Windows\Cursors and allows the user to click on an image of the cursor they want and have it applied. Thanks for reading.
I've been trying to convert the .cur file to .jpeg because I think this is the reason that it is not being displayed under flowLayoutPanel1 but it is still not working.
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO;
using System.Windows.Forms;
using System.Drawing.Imaging;
using ImageMagick;
namespace CrossHare
{
public partial class Form1 : Form
{
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool SystemParametersInfo(int uiAction, int uiParam, IntPtr pvParam, int fWinIni);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr LoadCursorFromFile(string lpFileName);
private const int SPI_SETCURSORS = 0x0057;
private const int SPIF_UPDATEINIFILE = 0x01;
private const int SPIF_SENDCHANGE = 0x02;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Get the file paths of all files in the directory
string[] files = Directory.GetFiles(#"C:\Windows\Cursors");
// Iterate through the file paths
foreach (string file in files)
{
// Check if the file is an image file
if (!file.EndsWith(".cur")) continue;
try
{
// Create a new button
Button btn = new Button();
//Convert cur file to jpeg
using (MagickImage image = new MagickImage(file))
{
string jpegFile = Path.ChangeExtension(file, ".jpeg");
image.Format = MagickFormat.Jpeg;
image.Write(jpegFile);
using (Image img = Image.FromFile(jpegFile))
{
btn.Tag = file;
btn.Image = img;
}
}
btn.Size = new Size(100, 100);
btn.Click += Button_Click;
flowLayoutPanel1.Controls.Add(btn);
}
catch (FileNotFoundException ex)
{
// Handle file not found exception
MessageBox.Show("Error: " + ex.Message);
}
catch (OutOfMemoryException ex)
{
// Handle out of memory exception
MessageBox.Show("Error: " + ex.Message);
}
}
}
private void Button_Click(object sender, EventArgs e)
{
// Handle button click event
MessageBox.Show("Button clicked!");
// Get the selected file's path
string filePath = ((Button)sender).Image.Tag as string;
// Set the selected file as the "normal select" pointer in "Mouse properties"
RegistryKey key = Registry.CurrentUser.OpenSubKey("Control Panel\\Cursors", true);
key.SetValue("Arrow", filePath);
key.Close();
IntPtr hCursor = new IntPtr((int)LoadCursorFromFile(filePath));
SystemParametersInfo(SPI_SETCURSORS, 0, hCursor, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);
}
private void UploadButton_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Cursor files (*.cur)|*.cur|All files (*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
// Get the selected file's path
string filePath = openFileDialog.FileName;
// Do something with the file (e.g. upload it to a server)
string destinationPath = #"C:\Windows\Cursors";
string destinationFilePath = Path.Combine(destinationPath, Path.GetFileName(filePath));
if (File.Exists(destinationFilePath))
{
DialogResult result = MessageBox.Show("File already exists, do you want to overwrite it?", "File Exists", MessageBoxButtons.YesNo);
if (result == DialogResult.No)
{
return;
}
}
File.Copy(filePath, destinationFilePath, true);
}
}
}
}
After carefully reading your code, if I'm following correctly your objectives are:
Display all the available cursors in a FlowLayoutPanel.
Click on an image to change the current cursor.
What we end up with here could be considered an X-Y Problem because doing that is straightforward, but the manner in which you're trying to solve your problem is not.
Please allow me to steer the conversation back to what you were trying to do to begin with:
To achieve this objective, use reflection to obtain the cursors from the Cursors class, draw each one, and place a corresponding button in the FlowLayoutPanel.
public partial class MainForm : Form
{
public MainForm()=>InitializeComponent();
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
foreach (PropertyInfo pi in typeof(Cursors).GetProperties(BindingFlags.Static | BindingFlags.Public))
{
if(pi.GetValue(null) is Cursor cursor)
{
var image = new Bitmap(100, 100);
using (var graphics = Graphics.FromImage(image))
{
cursor.DrawStretched(
graphics,
new Rectangle(new Point(), new Size(image.Width, image.Height)));
}
var button = new Button
{
Size = image.Size,
BackgroundImage = image,
BackgroundImageLayout = ImageLayout.Stretch,
Margin = new Padding(5),
Tag = cursor,
};
button.Click += onAnyClickCursorButton;
// Avoid confusion - see note.
button.MouseHover += (sender, e) => Cursor = Cursors.Default;
flowLayoutPanel.Controls.Add(button);
}
}
}
By attaching a Click event to each button, the current Cursor can be changed to the one clicked. To avoid visual confusion, if a different button is hovered over then return to the default cursor to more clearly indicate that the new style can now be clicked.
private void onAnyClickCursorButton(object? sender, EventArgs e)
{
if((sender is Button button) && (button.Tag is Cursor cursor))
{
Cursor = cursor;
}
}
}

Adding Page Numbers

I haven't really written anything outside of Powershell in a long time, and I know this is ugly, but I can't seem to figure out why my new PDF is not adding the page numbers. I pulled the example from this itext kb.
I tried to make this basic app so people in the office could add the page numbers to PDF's. Here's what I have so far. It will create the new PDF (duplicate of the original), but it's not adding the page numbers.
Basically they use button1 to find their PDF via the Windows File Explorer dialog. It just stores the filename in a textbox. The second button is the "save" and should take the src file and make a copy of the src with only adding the page number at the bottom of the file (or anywhere at this point).
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
namespace PDFManipulation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
textBox1.Text = file;
}
catch (System.IO.IOException)
{
}
}
Console.WriteLine(size); // <-- Shows file size in debugging mode.
Console.WriteLine(result); // <-- For debugging use.
}
private void button2_Click(object sender, EventArgs e)
{
Stream myStream;
//SaveFileDialog saveFileDialog1 = new SaveFileDialog();
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
string SRC = textBox1.Text;
string DEST = saveFileDialog1.FileName;
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST));
Document doc = new Document(pdfDoc);
int numberOfPages = pdfDoc.GetNumberOfPages();
for (int i = 1; i <= numberOfPages; i++)
{
// Write aligned text to the specified by parameters point
doc.ShowTextAligned(new Paragraph("page " + i + " of " + numberOfPages),559, 806, i, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
}
doc.Close();
}
}
MessageBox.Show("PDF Page Numbering Added!", "Pages Added",MessageBoxButtons.OK);
Application.Exit();
}
}
}
I'm a dumb dumb. The x,y coordinates were off as the value 812 for the height is off the page.

Record audio from a media player

How do I record audio from my media player using c# winforms.
I'm trying to create an app that records audio from a player(vlc) and then saves it to my computer.
Any idea will be highly appreciated.
What do you mean using your media player? If you simply want to do it using C# just use the winmm.dll library.
Import the namespace.
using System.Runtime.InteropServices;
Declare the interop function
[DllImport("winmm.dll",EntryPoint="mciSendStringA", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)]
private static extern int record(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);
Start recording
record("open new Type waveaudio Alias recsound", "", 0, 0);
record("record recsound", "", 0, 0);
Stop recording and save to file
record("save recsound d:\myRecordedAudioFile.wav", "", 0, 0);
record("close recsound", "", 0, 0);
You can use NAudio, here is a quick sample
Two buttons Record and Stop,
public WaveIn _waveIn = null;
public WaveFileWriter fileToWrite = null;
private void btn_record_Click(object sender, EventArgs e) {
_waveIn = new WaveIn();
_waveIn.WaveFormat = new WaveFormat(44100, 1);
_waveIn.DataAvailable += _waveIn_DataAvailable; // event that keep listening mic
fileToWrite = new WaveFileWriter(#"C:\Users\userName\Documents\myFile.wav", _waveIn.WaveFormat);
_waveIn.StartRecording();
}
private void _waveIn_DataAvailable(object sender, WaveInEventArgs e) {
if (fileToWrite != null) {
fileToWrite.Write(e.Buffer, 0, e.BytesRecorded); // writes bytes to the wav file
fileToWrite.Flush();
}
}
private void btn_stop_Click(object sender, EventArgs e) {
_waveIn.StopRecording();
}
Hope helps,

C# assignment, Binary file types

I am a starting student in C# and I can't find the answer for the following question:
"Write a program to open a text file and save the individual high and low 4 bit nibbles of each byte and in a binary file. Write a program to do the reerse, i.e reads two bytes from a binary file, combines them and writes them as a text file."
I can read code, and understand it. But since i'm new to this field, it's hard for me to actually come up on it completely on my own.
I've already wrote the code to open a .txt file and to save it as an .txt file.
Image of form1: Since I lack the "reputation" I can't post images. :(
And this is the code I wrote:
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;
namespace _9._3_menustripAndFiledialog
{
public partial class Form1 : Form
{
private System.Drawing.Printing.PrintDocument docToPrint =
new System.Drawing.Printing.PrintDocument();
public Form1()
{
InitializeComponent();
}
private void helpToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
//Clear rich text box
richTextBox1.Clear();
//Set open file dialog initial directory and title
openFileDialog1.InitialDirectory = #"C:\"; //Hier zeg je welke directory drive hij moet openen
openFileDialog1.Title = "Please select a file";
openFileDialog1.Filter= "Text files(*.TXT)|*.txt";
MessageBox.Show("Only .txt files can be opened.");
//Open the dialog and check for cancel
if (openFileDialog1.ShowDialog() != DialogResult.Cancel)
{
// niet gecanceled - lees bestand
richTextBox1.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.PlainText);
}
else
{
MessageBox.Show("Gosh darn it! You pressed cancel!");
}
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if(saveFileDialog1.ShowDialog() != DialogResult.Cancel)
{
// niet gecanceld - schrijf het bestand
richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
} else {
MessageBox.Show("You pressed cancel!");
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
// Display a message box asking users if they
// want to exit the application.
if (MessageBox.Show("Do you want to exit?", "My Application",
MessageBoxButtons.YesNo, MessageBoxIcon.Question)
== DialogResult.Yes)
{
Application.Exit();
}
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
AboutBox1 frmAbout = new AboutBox1();
frmAbout.Show();
}
private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Cut();
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Paste();
}
private void undoToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Undo();
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Copy();
}
private void redoToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Redo();
}
private void findTextToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Find("Text", RichTextBoxFinds.MatchCase);
richTextBox1.SelectionFont = new Font("Verdana", 12, FontStyle.Italic);
richTextBox1.SelectionColor = Color.Blue;
}
public void replaceTextToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Text = richTextBox1.Text.Replace("Text", "newText");
}
private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
printDialog1.AllowSomePages = true;
printDialog1.ShowHelp = true;
printDialog1.Document = docToPrint;
DialogResult result = printDialog1.ShowDialog();
if (result == DialogResult.OK)
{
docToPrint.Print();
}
}
//Code starting from here are added from user: Xanatos
public static void ReadSplitWrite(string inputFile, string outputFile)
{
using (var sr = File.OpenRead(inputFile))
using (var sw = File.Create(outputFile))
{
int read;
byte[] inputBuffer = new byte[4096];
byte[] outputBuffer = new byte[inputBuffer.Length * 2];
while ((read = sr.Read(inputBuffer, 0, inputBuffer.Length)) != 0)
{
for (int i = 0, j = 0; i < read; i++, j += 2)
{
outputBuffer[j] = (byte)(inputBuffer[i] & 0x0F);
outputBuffer[j + 1] = (byte)(inputBuffer[i] & 0xF0);
}
sw.Write(outputBuffer, 0, read * 2);
}
}
}
public static void ReadMergeWrite(string inputFile, string outputFile)
{
using (var sr = File.OpenRead(inputFile))
using (var sw = File.Create(outputFile))
{
int read;
byte[] inputBuffer = new byte[4096 * 2];
byte[] outputBuffer = new byte[inputBuffer.Length / 2];
while ((read = sr.Read(inputBuffer, 0, inputBuffer.Length)) != 0)
{
for (int i = 0, j = 0; i < read; i += 2, j++)
{
outputBuffer[j] = inputBuffer[i];
outputBuffer[j] |= inputBuffer[i + 1];
}
sw.Write(outputBuffer, 0, read / 2);
}
}
}
//I made a custom button to support the read and write method and to have it inside my form
private void openAndSaveAsBinaryToolStripMenuItem_Click(object sender, EventArgs e)
{
ReadSplitWrite("inputfile.txt", "output.dat");
ReadMergeWrite("output.dat", "inputfile2.txt");
}
}
}
I would really appreciate some help on this matter! :)
Thanks in advance!
I tried something and this is what I came up with as sollution to the question.
private void openAndSaveAsBinaryToolStripMenuItem_Click(object sender, EventArgs e)
{
string dirPath = #"C:\";
//read from folder: C:\
//create directory if it doesn't exist
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
string fileName = #dirPath + "/TestFile.bin";
//Create binary file if it doesn't exist
if (!File.Exists(fileName))
{
//File doesn't exist - create file
FileStream fs = new FileStream(fileName, FileMode.CreateNew);
BinaryWriter bw = new BinaryWriter(fs);
byte[] byteArray = { 0x48, 0x45, 0x4C, 0x4C, 0x4F }; //HELLO!
for (int i = 0; i < byteArray.Length; i++)
{
bw.Write(byteArray[i]);
}
bw.Close();
fs.Close();
}
// reads back
FileStream fsRead = new FileStream(fileName, FileMode.Open);
BinaryReader br = new BinaryReader(fsRead);
for (int i = 0; i < fsRead.Length; i++)
{
MessageBox.Show(br.ReadByte().ToString());
}
br.Close();
fsRead.Close();
}
What it does: It creates a new directory if it doesn't exists. Also, it writes the .bin file now and returns it to me in a MessageBox as Binary. (Converted .ToString()). After that it saved it in the directory,and it converts it in the .bin to readable text.
I think this is what the assignment asked from me.
I want to thank you folks for the help, without it I couldn't have done it :)
Here there are two methods, the first one splits, the second one merges. Note that your assignment isn't clear if you have to shift the second nibble after splitting it or not... To make it clear:
0xFF
should I split it to:
0x0F 0xF0
or to
0x0F 0x0F
I choose the first one.
public static void ReadSplitWrite(string inputFile, string outputFile)
{
using (var sr = File.OpenRead(inputFile))
using (var sw = File.Create(outputFile))
{
int read;
byte[] inputBuffer = new byte[4096];
byte[] outputBuffer = new byte[inputBuffer.Length * 2];
while ((read = sr.Read(inputBuffer, 0, inputBuffer.Length)) != 0)
{
for (int i = 0, j = 0; i < read; i++, j += 2)
{
outputBuffer[j] = (byte)(inputBuffer[i] & 0x0F);
outputBuffer[j + 1] = (byte)(inputBuffer[i] & 0xF0);
}
sw.Write(outputBuffer, 0, read * 2);
}
}
}
public static void ReadMergeWrite(string inputFile, string outputFile)
{
using (var sr = File.OpenRead(inputFile))
using (var sw = File.Create(outputFile))
{
int read;
byte[] inputBuffer = new byte[4096 * 2];
byte[] outputBuffer = new byte[inputBuffer.Length / 2];
while ((read = sr.Read(inputBuffer, 0, inputBuffer.Length)) != 0)
{
for (int i = 0, j = 0; i < read; i += 2, j++)
{
outputBuffer[j] = inputBuffer[i];
outputBuffer[j] |= inputBuffer[i + 1];
}
sw.Write(outputBuffer, 0, read / 2);
}
}
}
Use it like:
ReadSplitWrite("inputfile.txt", "output.dat");
ReadMergeWrite("output.dat", "inputfile2.txt");
If you look at the example, you will see that I read the file at blocks of 4096/8192 bytes at a time (inputBuffer), and then I have a second buffer where I put the splitted/merged bytes that I then write.

How to take screenshot of webpage in C#

I am totally new to C# coding - I am trying to take screen shots of webpages whose URLs are initially picked up form a notepad uploaded on the same form.
As I read through the documentation on the web_browser control in MSDN.. I did arrive at the following code - yet when I run, I only get white screens
I tried uploading a .txt with (google/yahoo URLs as test data in 2 lines)
Can someone please say what more should I take care apart from handling which should get what I want as I read in MSDN.
P.S: pls forgive if I'm terribly wrong in coding style .. as aforesaid I'm just starting my C# coding :)
Code that I tried...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MSDN_wbc_tut1
{
public partial class Form1 : Form
{
public int temp = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void FileUploadButton1_Click(object sender, EventArgs e)
{
//once a file is uploaded i want Pgm to read contents & browse them as URLS
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.CheckFileExists = true;
openFileDialog.AddExtension = true;
openFileDialog.Multiselect = true;
//Filtering for Text files alone
openFileDialog.Filter = "text files (*.txt)|*.txt";
//if file is selected we must then do our coding part to proceed hecneforth
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//my code to say pgm wat to do once upload done...
//Getting my Chosen file's name
string Fileuploaded = openFileDialog.FileName;
//Read all line opens files - reads till EOF & closes ,prevents a while condition
string[] FileuploadedContent = System.IO.File.ReadAllLines(Fileuploaded);
foreach (string s in FileuploadedContent)
{
NavigateContent(s);
}
}
}
private void NavigateContent(string lineasurl)
{
// Add an event handler that images the document after it loads.
try
{
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler
(takescreen);
webBrowser1.Navigate(new Uri(lineasurl));
//webBrowser1.Navigate(lineasurl); also works
}
catch (System.UriFormatException)
{
return;
}
}
private void takescreen(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//specifying sample values for image or screenshot size
int x = 600, y = 700;
Bitmap bitmap = new Bitmap(x, y);
webBrowser1.DrawToBitmap(bitmap, new Rectangle(0, 0, x, y));
//to give each screen a unique name - i append some no onto it
temp = temp + 1;
string TempFname = "Screenshotref" + temp.ToString() + "." + "jpg";
bitmap.Save(TempFname);
}
}
}

Categories

Resources