Play a video with MediaElement and download it too - c#

I want to play a video from the web in MediaElement and in the same time to download the video too.
I try to do it with setting Stream as the source but it won't work. It is possible to do it?
EDIT:
This is what i do for now,the problem is that i want to start playing from the start and not when i finish download the file:
public void StartDownloadFile(string aVideoUrl,string aId)
{
this.VideoUrl = aVideoUrl;
this.id = aId;
startPlaying = false;
WebClient webClient = new WebClient();
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
webClient.OpenReadAsync(new Uri(this.VideoUrl));
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
try
{
if (e.Result != null)
{
#region Isolated Storage Copy Code
isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication();
bool checkQuotaIncrease = this.IncreaseIsolatedStorageSpace(e.Result.Length);
string VideoFile = "VideoCache\\" + this.id + ".wmv";
isolatedStorageFileStream = new IsolatedStorageFileStream(VideoFile, FileMode.Create, isolatedStorageFile);
long VideoFileLength = (long)e.Result.Length;
byte[] byteImage = new byte[VideoFileLength];
e.Result.Read(byteImage, 0, byteImage.Length);
isolatedStorageFileStream.Write(byteImage, 0, byteImage.Length);
#endregion
callbackFinish();
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
try
{
callbackDidUpdate((double)e.ProgressPercentage);
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
}

Related

Recording audio with NAudio cuts me off

I am recording an audio to send it to send it to Google speech to text but when I make the audio with naudio it records me only 5 seconds and from there it stops recording. I copy the code in C #, this is my first time using this API, but I don't know why it cuts me, if it should stop recording when I press the save button, the application is a simple form with 2 buttons, one for recording and the other for stop.
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private BufferedWaveProvider bwp;
WaveIn waveIn;
WaveOut waveOut;
WaveFileWriter writer;
WaveFileReader reader;
string output = "audio.raw";
public Form1()
{
InitializeComponent();
waveOut = new WaveOut();
waveIn = new WaveIn();
waveIn.DataAvailable += new EventHandler<WaveInEventArgs>(waveIn_DataAvailable);
waveIn.WaveFormat = new NAudio.Wave.WaveFormat(16000, 1);
bwp = new BufferedWaveProvider(waveIn.WaveFormat);
bwp.DiscardOnBufferOverflow = true;
btnRecordVoice.Enabled = true;
btnSave.Enabled = false;
//btnSpeechInfo.Enabled = false;
}
private void btnRecordVoice_Click(object sender, EventArgs e)
{
if (NAudio.Wave.WaveIn.DeviceCount < 1)
{
Console.WriteLine("No se encuentra un microfono!");
return;
}
waveIn.StartRecording();
btnRecordVoice.Enabled = false;
btnSave.Enabled = true;
}
private void btnSave_Click(object sender, EventArgs e)
{
waveIn.StopRecording();
if (File.Exists("audio.raw"))
File.Delete("audio.raw");
writer = new WaveFileWriter(output, waveIn.WaveFormat);
btnRecordVoice.Enabled = false;
btnSave.Enabled = false;
byte[] buffer = new byte[bwp.BufferLength];
int offset = 0;
int count = bwp.BufferLength;
var read = bwp.Read(buffer, offset, count);
if (count > 0)
{
writer.Write(buffer, offset, read);
}
waveIn.Dispose();
waveIn = null;
writer.Close();
writer = null;
reader = new WaveFileReader("audio.raw"); // (new MemoryStream(bytes));
waveOut.Init(reader);
waveOut.PlaybackStopped += new EventHandler<StoppedEventArgs>(waveOut_PlaybackStopped);
waveOut.Play();
}
void waveIn_DataAvailable(object sender, WaveInEventArgs e)
{
bwp.AddSamples(e.Buffer, 0, e.BytesRecorded);
}
private void waveOut_PlaybackStopped(object sender, StoppedEventArgs e)
{
waveOut.Stop();
reader.Close();
reader = null;
}
}
}
You get a 5-second audio clip not only because you do a one-time BufferLength read from the BufferedWaveProvider...
int count = bwp.BufferLength;
var read = bwp.Read(buffer, offset, count);
...and 5 seconds is the default value of that property, but because BufferedWaveProvider uses a circular buffer, so BufferLength is all the data it has available.
What worked for me was to skip the BufferedWaveProvider and write new data to the WaveFileWriter as soon as it becomes available...
void waveIn_DataAvailable(object sender, WaveInEventArgs e)
{
writer.Write(e.Buffer, 0, e.BytesRecorded);
}
To support that change, the button event handlers get changed to the following...
private void btnRecordVoice_Click(object sender, EventArgs e)
{
if (NAudio.Wave.WaveIn.DeviceCount < 1)
{
Console.WriteLine("No se encuentra un microfono!");
return;
}
writer = new WaveFileWriter(output, waveIn.WaveFormat);
waveIn.StartRecording();
btnRecordVoice.Enabled = false;
btnSave.Enabled = true;
}
private void btnSave_Click(object sender, EventArgs e)
{
waveIn.StopRecording();
writer.Close();
writer = null;
btnRecordVoice.Enabled = false;
btnSave.Enabled = false;
reader = new WaveFileReader("audio.raw"); // (new MemoryStream(bytes));
waveOut.Init(reader);
waveOut.PlaybackStopped += new EventHandler<StoppedEventArgs>(waveOut_PlaybackStopped);
waveOut.Play();
}
This appears to be the same approach used in Recording a WAV file in a WinForms app with WaveIn.

How to move a function to a separate assembly from the interface [Error]

I am currently working on a file copying facility that allows me to select a source and a destination for the folders to be copied from and to. A progress bar is displayed after the user clicks on Copy.
The only issue is that All of my functions reside in one file which is form1.cs (as follows)
namespace CopyFacility
{
public partial class Form1 : Form
{
BackgroundWorker background = new BackgroundWorker();
FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
OpenFileDialog openFile = new OpenFileDialog();
public Form1()
{
InitializeComponent();
background.WorkerSupportsCancellation = true;
background.WorkerReportsProgress = true;
background.DoWork += Background_DoWork;
background.RunWorkerCompleted += Background_RunWorkerCompleted;
background.ProgressChanged += Background_ProgressChanged;
}
string inputFile = null;
string outputFile = null;
private void CopyFile(string source, string destination, DoWorkEventArgs e)
{
FileStream fsOut = new FileStream(destination, FileMode.Create);
FileStream fsIn = new FileStream(source, FileMode.Open);
byte[] buffer = new byte[1048756];
int readBytes;
while((readBytes = fsIn.Read(buffer,0,buffer.Length)) > 0)
{
if(background.CancellationPending)
{
e.Cancel = true;
background.ReportProgress(0);
fsIn.Close();
fsOut.Close();
return;
}
else
{
fsOut.Write(buffer, 0, readBytes);
background.ReportProgress((int) (fsIn.Position * 100 / fsIn.Length));
}
fsOut.Write(buffer, 0, readBytes);
background.ReportProgress((int)(fsIn.Position * 100 / fsIn.Length));
}
fsIn.Close();
fsOut.Close();
}
private void Background_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
fileProgressBar.Value = e.ProgressPercentage;
}
private void Background_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if(e.Cancelled)
{
fileProgressBar.Visible = true;
lblMessage.Visible = true;
lblMessage.Text = "The process has been cancelled";
}
else
{
fileProgressBar.Visible = true;
lblMessage.Visible = true;
lblMessage.Text = "The process has been completed";
}
}
private void Background_DoWork(object sender, DoWorkEventArgs e)
{
CopyFile(inputFile, outputFile + #"\" + Path.GetFileName(inputFile),e);
}
private void btnCancel_Click(object sender, EventArgs e)
{
background.CancelAsync();
}
private void btnCopy_Click(object sender, EventArgs e)
{
if(background.IsBusy)
{
lblProgress.Visible = true;
}
else
{
fileProgressBar.Visible = true;
background.RunWorkerAsync();
}
}
private void btnSource_Click(object sender, EventArgs e)
{
if(openFile.ShowDialog() == DialogResult.OK )
{
inputFile = openFile.FileName;
btnSource.Text = inputFile;
}
}
private void btnDestination_Click(object sender, EventArgs e)
{
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
outputFile = folderBrowser.SelectedPath;
btnDestination.Text = outputFile + #"\" + Path.GetFileName(inputFile);
}
}
}
}
I was wondering how I could go about putting the function "CopyFile" into it's own class that can be called whenever the button is clicked?
When I try creating a new class method and inserting the functions related to the copying function into a new class "CopyFunction.cs" , I get a following error from the code "InitializingComponent();" as follows
public CopyPresenter(BackgroundWorker background, FolderBrowserDialog folderBrwoser, OpenFileDialog openFile)
{
InitializeComponent();
background.WorkerSupportsCancellation = true;
background.WorkerReportsProgress = true;
background.DoWork += Background_DoWork;
background.RunWorkerCompleted += Background_RunWorkerCompleted;
background.ProgressChanged += Background_ProgressChanged;
}
The error says that the "InitializeComponent" doesn't exist in the current context.

Record live audio from mic input and save simultanously

I was trying to develop a Voice recorder in C#. I have tried many ways, like NAudio, DirectX, Microsoft.Xna.Framework.Audio, etc.
Everything gives the same result. After we stop the recording, the output file mp3/wav get saved.
The mp3/wav file get created at the beginning itself (without and content - 0 bytes)
I am trying to create an application which can save audio live/simultaneously.
private void StartRecording() {
this.WaveSource = new WaveInEvent { WaveFormat = new WaveFormat(44100, 1) };
this.WaveSource.DataAvailable += this.WaveSourceDataAvailable;
this.WaveSource.RecordingStopped += this.WaveSourceRecordingStopped;
this.WaveFile = new WaveFileWriter(#"C:\Sample.wav", this.WaveSource.WaveFormat);
this.WaveSource.StartRecording();
}
private void StopRecording() {
this.WaveSource.StopRecording();
}
void WaveSourceDataAvailable(object sender, WaveInEventArgs e) {
if (this.WaveFile != null) {
this.WaveFile.Write(e.Buffer, 0, e.BytesRecorded);
this.WaveFile.Flush();
}
}
void WaveSourceRecordingStopped(object sender, StoppedEventArgs e) {
if (this.WaveSource != null) {
this.WaveSource.Dispose();
this.WaveSource = null;
}
if (this.WaveFile != null) {
this.WaveFile.Dispose();
this.WaveFile = null;
}
}
I have solved the problem with NAudio library itself.
Few modification to the existing code.
public class Recorder {
WaveIn sourceStream;
WaveFileWriter waveWriter;
readonly String FilePath;
readonly String FileName;
readonly int InputDeviceIndex;
public Recorder(int inputDeviceIndex, String filePath, String fileName) {
InitializeComponent();
this.InputDeviceIndex = inputDeviceIndex;
this.FileName = fileName;
this.FilePath = filePath;
}
public void StartRecording(object sender, EventArgs e) {
sourceStream = new WaveIn {
DeviceNumber = this.InputDeviceIndex,
WaveFormat =
new WaveFormat(44100, WaveIn.GetCapabilities(this.InputDeviceIndex).Channels)
};
sourceStream.DataAvailable += this.SourceStreamDataAvailable;
if (!Directory.Exists(FilePath)) {
Directory.CreateDirectory(FilePath);
}
waveWriter = new WaveFileWriter(FilePath + FileName, sourceStream.WaveFormat);
sourceStream.StartRecording();
}
public void SourceStreamDataAvailable(object sender, WaveInEventArgs e) {
if (waveWriter == null) return;
waveWriter.Write(e.Buffer, 0, e.BytesRecorded);
waveWriter.Flush();
}
private void RecordEnd(object sender, EventArgs e) {
if (sourceStream != null) {
sourceStream.StopRecording();
sourceStream.Dispose();
sourceStream = null;
}
if (this.waveWriter == null) {
return;
}
this.waveWriter.Dispose();
this.waveWriter = null;
recordEndButton.Enabled = false;
Application.Exit();
Environment.Exit(0);
}
}
You can do this with DirectShow.
Take a look at Microsoft's documentation and the project's code samples to learn the best way to configure it according to your needs.
Wanna try to BASS NET?
There is a complete code for you task How to record sound and encode it to mp3? (C#!)

Windows Phone - Isolated Storage exception

The code below catch the server path chosen by the user and saves on IsolatedStorage:
private void ConfSalvar(object sender, RoutedEventArgs e)
{
IsolatedStorageSettings iso = IsolatedStorageSettings.ApplicationSettings;
if (iso.Contains("isoServer"))
{
iso["isoServer"] = server.Text;
}
else
{
iso.Add("isoServer", server.Text);
}
}
The next code (another screen), uses the server path saved on IsolatedStorage for make an URL:
IsolatedStorageSettings iso = IsolatedStorageSettings.ApplicationSettings;
if (iso.TryGetValue<string>("isoServer", out retornaNome))
{
serv = retornaNome;
}
private void sinc(object sender, EventArgs e)
{
order.Visibility = Visibility.Collapsed;
client = new WebClient();
url = serv + "/json.html";
Uri uri = new Uri(url, UriKind.RelativeOrAbsolute);
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.OpenReadAsync(uri);
}
private void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
string strFileName = url.Substring(url.LastIndexOf("/") + 1, (url.Length - url.LastIndexOf("/") - 1));
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
// Path Storage
// *** If File Exists
if (isoStore.FileExists(strFileName))
{
isoStore.DeleteFile(strFileName);
}
IsolatedStorageFileStream dataFile = new IsolatedStorageFileStream(strFileName, FileMode.CreateNew, isoStore);
long fileLen = e.Result.Length;
byte[] b = new byte[fileLen];
e.Result.Read(b, 0, b.Length);
dataFile.Write(b, 0, b.Length);
dataFile.Flush();
object lenghtOfFile = dataFile.Length;
dataFile.Close();
order.Visibility = Visibility.Visible;
ProgressBar1.Visibility = Visibility.Collapsed;
MessageBox.Show("Arquivo salvo!");
}
private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
ProgressBar1.Visibility = Visibility.Visible;
this.ProgressBar1.Value = e.ProgressPercentage;
}
So, if I saved the file path and immediately after click the button "sinc", an exception "An exception occurred during the operation, making the result invalid. Check InnerException for exception details.".
But if I saved the file path and close the app, open the app and click the "sinc" button, it works.
Sorry for bad english
This had nothing to do with the IsolatedStorageSettings. It works fine. The problem was when you were creating the Uri you set the UriKind as RelativeOrAbsolute.
Thats what threw the Exception and InnerException states that This operations is not supported for a relative URI. What you need to do is change the UriKind to Absolute. So the code block should look like this.
private void sinc(object sender, EventArgs e)
{
if (iso.TryGetValue<string>("isoServer", out retornaNome))
{
serv = retornaNome;
}
else
{
// Let the user know.
return;
}
order.Visibility = Visibility.Collapsed;
client = new WebClient();
url = serv + "/json.html";
Uri uri = new Uri(url, UriKind.Absolute); // <<< Absolute instead of RelativeOrAbsolute
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.OpenReadAsync(uri);
}
That should fix your problem and work just fine :)

C# upload file by webclient

I uploaded a file by webclient. But upload success and response link file. But when I go to the file manager I don't have the file in my account. Why ?
This is my code.
private void btnUpload_Click(object sender, EventArgs e)
{
WebClient wc = new WebClient();
wc.Headers.Add("OurSecurityHeader", "encryptedvalue");
wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
wc.Headers.Add(HttpRequestHeader.Cookie, "__cfduid=d56b9e4ca0801822e9231936c70518ec91397746478931; __utma=259844498.1111893290.1397796877.1397796877.1397802609.2; __utmc=259844498; __utmz=259844498.1397796877.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); login=KimJanParkC1; xfss=g7prlsjg15zl57h4; __zlcid=%7B%22mID%22%3A%22OPdgp3o75YUWIg%22%2C%22sid%22%3A%22140417.91047.473AFH5T%22%7D; __utmb=259844498.17.10.1397802609; sthumb=500x500; _mcnc=1");
wc.UploadProgressChanged += new UploadProgressChangedEventHandler(wc_UploadProgressChanged);
wc.UploadFileCompleted += new UploadFileCompletedEventHandler(UploadFileCallback);
wc.UploadFileAsync(new Uri("http://img102.imagetwist.com/cgi-bin/upload.cgi?upload_id="), "POST", txtPath.Text);
}
void wc_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
{
// GET DOWNLOAD LINK
MessageBox.Show("Upload Finished");
}
void wc_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
pgbStatus.Maximum = (int)e.TotalBytesToSend;
pgbStatus.Value = (int)e.BytesSent;
label6.Text = ((int)e.BytesSent * 100) / (int)e.TotalBytesToSend + "%";
}
public void UploadFileCallback(Object sender, UploadFileCompletedEventArgs e)
{
// GET RESPOND DOWNLOAD LINK
HtmlAgilityPack.HtmlDocument hd = new HtmlAgilityPack.HtmlDocument();
hd.LoadHtml(System.Text.Encoding.UTF8.GetString(e.Result));
txtResult.Text = hd.DocumentNode.InnerHtml;
}
In windows side:
private void uploadButton_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog();
var dialogResult = openFileDialog.ShowDialog();
if (dialogResult != DialogResult.OK) return;
Upload(openFileDialog.FileName);
}
private void Upload(string fileName)
{
var client = new WebClient();
client.UploadFileCompleted += new UploadFileCompletedEventHandler(Completed);
client.UploadProgressChanged += new UploadProgressChangedEventHandler(ProgressChanged);
var uri = new Uri("http://www.yoursite.com/UploadFile/");
try
{
client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
var data = System.IO.File.ReadAllBytes(fileName);
client.UploadDataAsync(uri, data);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Completed(object sender, UploadFileCompletedEventArgs e)
{
MessageBox.Show(e.Error?.Message ?? "Uploaded Successfully!");
}
private void ProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
In server side you should use WebApi:
[HttpPost]
public async Task<object> UploadFile()
{
var file = await Request.Content.ReadAsByteArrayAsync();
var fileName = Request.Headers.GetValues("fileName").FirstOrDefault();
var filePath = "/upload/files/";
try
{
File.WriteAllBytes(HttpContext.Current.Server.MapPath(filePath) + fileName , file);
}
catch (Exception ex)
{
// ignored
}
return null;
}

Categories