I am working on a project that extracts YouTube videos' audio and saves them to your computer. To do this, I used a library from GitHub called YouTubeExtractor.
I am using a backgroundworker in order to make the UI usable while the file is being downloaded. This is the code I have so far.
public partial class MainWindow : Window
{
private readonly BackgroundWorker worker = new BackgroundWorker();
public MainWindow()
{
InitializeComponent();
worker.DoWork += worker_DoWork;
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
}
private void downloadButton_Click(object sender, RoutedEventArgs e)
{
worker.RunWorkerAsync();
}
string link;
double percentage;
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
this.Dispatcher.Invoke((Action)(() =>
{
link = videoURL.Text;
}));
/*
* Get the available video formats.
* We'll work with them in the video and audio download examples.
*/
IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link);
/*
* We want the first extractable video with the highest audio quality.
*/
VideoInfo video = videoInfos
.Where(info => info.CanExtractAudio)
.OrderByDescending(info => info.AudioBitrate)
.First();
/*
* If the video has a decrypted signature, decipher it
*/
if (video.RequiresDecryption)
{
DownloadUrlResolver.DecryptDownloadUrl(video);
}
/*
* Create the audio downloader.
* The first argument is the video where the audio should be extracted from.
* The second argument is the path to save the audio file.
*/
var audioDownloader = new AudioDownloader(video, System.IO.Path.Combine("C:/Downloads", video.Title + video.AudioExtension));
// Register the progress events. We treat the download progress as 85% of the progress and the extraction progress only as 15% of the progress,
// because the download will take much longer than the audio extraction.
audioDownloader.DownloadProgressChanged += (send, args) => Console.WriteLine(args.ProgressPercentage * 0.85);
audioDownloader.AudioExtractionProgressChanged += (send, args) => Console.WriteLine(85 + args.ProgressPercentage * 0.15);
/*
* Execute the audio downloader.
* For GUI applications note, that this method runs synchronously.
*/
audioDownloader.Execute();
}
}
}
The problem I have is that I want to display this
audioDownloader.DownloadProgressChanged += (send, args) => Console.WriteLine(args.ProgressPercentage * 0.85);
audioDownloader.AudioExtractionProgressChanged += (send, args) => Console.WriteLine(85 + args.ProgressPercentage * 0.15);
In a UI element like a label or a progressbar instead of Console.WriteLine
Whenever I do label1.Text = (85 + args.ProgressPercentage * 0.15);
It throws me a an error like
" The calling thread cannot access this object because a different thread owns it."
I know you can do solve this with a delegate, I need a clear instruction on how so.
Thank you.