How could i update the windows audio playback agent properties like title and artist, live ,when it is playing. I want to update the title every 20 seconds without stopping the music which is playing? please help. I tried this but its stopping and replaying at every 20 seconds which is annoying. Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.BackgroundAudio;
using System.Threading;
using System.Windows.Threading;
namespace PhoneApp2
{
public partial class MainPage : PhoneApplicationPage
{
DispatcherTimer timer = new DispatcherTimer();
string Artist;
string Song;
// Constructor
public MainPage()
{
InitializeComponent();
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
timer.Interval = TimeSpan.FromSeconds(20);
timer.Start();
timer.Tick += timer_Tick;
}
void timer_Tick(object sender, EventArgs e)
{
WebClient client = new WebClient();
client.Encoding = System.Text.Encoding.UTF8;
client.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.Now.ToString();
client.DownloadStringAsync(new Uri("http://air-online2.hitfm.md/status_hitfm.xsl"));
client.DownloadStringCompleted += client_DownloadStringCompleted;
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string[] FullTitle = e.Result.Substring(166).Split('-');
Artist= FullTitle[0];
if(Artist.Contains(":"))
{
Artist=FullTitle[0].Replace(":",string.Empty);
}
Song = FullTitle[1].Replace(" ", string.Empty);
if (BackgroundAudioPlayer.Instance.PlayerState != PlayState.Playing)
{
BackgroundAudioPlayer.Instance.Track = new AudioTrack(new Uri("http://air-online2.hitfm.md/hitfm.mp3"), Artist, Song, null, null);
BackgroundAudioPlayer.Instance.Play();
}
else
{
BackgroundAudioPlayer.Instance.Track = new AudioTrack(new Uri("http://air-online2.hitfm.md/hitfm.mp3"), Artist, Song, null, null);
}
}
}
}
Related
I am trying to use SpeechRecognitionEngine in a C# application under Windows 11
I have tried the default microphone array that works with Cortana. I have tried an USB microphone and a bluetooth one. They all show they are working in Settings->Sound
I cannot get any of the events to fire including SpeechDetected and AudioStateChanged
Here is my code based on the Microsoft example:
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.Speech.Recognition;
using System.Diagnostics;
namespace Speech_Test
{
public partial class Form1 : Form
{
SpeechRecognitionEngine recognizer = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
recognizer = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-GB"));
Choices services = new Choices(new string[] { "restaurants", "hotels", "gas stations" });
Choices cities = new Choices(new string[] { "Seattle", "Boston", "Dallas" });
GrammarBuilder findServices = new GrammarBuilder("Find");
findServices.Append(services);
findServices.Append("near");
findServices.Append(cities);
Grammar servicesGrammar = new Grammar(findServices);
recognizer.LoadGrammarAsync(servicesGrammar);
recognizer.SpeechDetected +=
new EventHandler<SpeechDetectedEventArgs>(recognizer_SpeechDetected);
recognizer.AudioStateChanged +=
new EventHandler<AudioStateChangedEventArgs>(recognizer_AudioStateChanged);
// Add a handler for the speech recognized event.
recognizer.SpeechRecognized +=
new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
recognizer.SpeechRecognitionRejected +=
new EventHandler<SpeechRecognitionRejectedEventArgs>(recognizer_SpeechRejected);
// Configure the input to the speech recognizer.
recognizer.SetInputToDefaultAudioDevice();
recognizer.RecognizeAsync(RecognizeMode.Multiple);
//recognizer.EmulateRecognize("Find restaurants near Dallas");
}
catch (Exception ex)
{
Debug.WriteLine(ex.InnerException.Message);
}
}
// Handle the AudioStateChanged event.
private void recognizer_AudioStateChanged(object sender, AudioStateChangedEventArgs e)
{
Debug.WriteLine("The new audio state is: " + e.AudioState);
}
private void recognizer_SpeechDetected(object sender, SpeechDetectedEventArgs e)
{
Console.WriteLine(" Speech detected at AudioPosition = {0}", e.AudioPosition);
}
private void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
Debug.WriteLine("Recognized text: " + e.Result.Text);
}
private void recognizer_SpeechRejected(object sender, SpeechRecognitionRejectedEventArgs e)
{
Debug.WriteLine("Rejected text: " + e.Result.Text);
}
}
}
Any suggestions on how to find out why audio is not getting through?
Thanks
I'm learning wpf and at the same time developing an app with it. I'm having a hard time figuring out how i can run something when a doubleanimation (Or other sorts) is done. For instance:
DoubleAnimation myanim = new DoubleAnimation();
myanim.From = 10;
myanim.To = 100;
myanim.Duration = new Duration(TimeSpan.FromSeconds(3));
myview.BeginAnimation(Button.OpacityPropert, myanim);
//Code to do something when animation ends
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
namespace app
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
DoubleAnimation widthbutton = new DoubleAnimation();
widthbutton.From = 55;
widthbutton.To = 100;
widthbutton.Duration = new Duration(TimeSpan.FromSeconds(1.5));
button1.BeginAnimation(Button.HeightProperty, widthbutton);
DoubleAnimation widthbutton1 = new DoubleAnimation();
widthbutton1.From = 155;
widthbutton1.To = 200;
widthbutton1.Duration = new Duration(TimeSpan.FromSeconds(1.5));
button1.BeginAnimation(Button.WidthProperty, widthbutton1);
widthbutton.Completed += new EventHandler(myanim_Completed);
}
private void myanim_Completed(object sender, EventArgs e)
{
//your completed action here
MessageBox.Show("Animation done!");
}
}
}
How is this accomplishable? I have read quite a few other posts about this, but they all explain it using xaml, however i would like to do it using c# code. Thanks!
You can attach an event handler to the DoubleAnimation's Completed event.
myanim.Completed += new EventHandler(myanim_Completed);
private void myanim_Completed(object sender, EventArgs e)
{
//your completed action here
}
Or, if you prefer it inline, you can do
myanim.Completed += (s,e) =>
{
//your completed action here
};
Remember to attach the handler before starting the animation otherwise it won't fire.
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();
}
I wrote a code to update DDNS which works fine. I now need to run this code every n minutes: how would I go doing that?
I tried using:
while (true)
{
this.DoMyMethod();
Thread.Sleep(TimeSpan.FromMinutes(1));
}
and I am still having some trouble. What is the best way to run this task every n minutes?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Windows.Forms;
using System.Timers;
namespace GoogleDDNS
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (username.Text == "")
{
System.Windows.MessageBox.Show("Please enter the username");
username.Focus();
return;
}
if (password.Text == "")
{
System.Windows.MessageBox.Show("Please enter the password");
password.Focus();
return;
}
if (subdomain.Text == "")
{
System.Windows.MessageBox.Show("Please enter the subdomain");
subdomain.Focus();
return;
}
var client = new WebClient { Credentials = new NetworkCredential(username.Text, password.Text) };
var response = client.DownloadString("https://domains.google.com/nic/update?hostname=" + subdomain.Text);
responseddns.Content = response;
Properties.Settings.Default.usernamesave = username.Text;
Properties.Settings.Default.passwordsave = password.Text;
Properties.Settings.Default.subdomainsave = subdomain.Text;
Properties.Settings.Default.Save();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
username.Text = Properties.Settings.Default.usernamesave;
password.Text = Properties.Settings.Default.passwordsave;
subdomain.Text = Properties.Settings.Default.subdomainsave;
}
}
}
Why not using System.Threading.Timer to do so?
From the Microsoft documentation, say you have the following sample class:
class StatusChecker
{
private int invokeCount;
private int maxCount;
public StatusChecker(int count)
{
invokeCount = 0;
maxCount = count;
}
// This method is called by the timer delegate.
public void CheckStatus(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
Console.WriteLine("{0} Checking status {1,2}.",
DateTime.Now.ToString("h:mm:ss.fff"),
(++invokeCount).ToString());
if (invokeCount == maxCount)
{
// Reset the counter and signal the waiting thread.
invokeCount = 0;
autoEvent.Set();
}
}
}
Then you can create a Timer to run CheckStatus every n seconds, like:
// Create an AutoResetEvent to signal the timeout threshold in the
// timer callback has been reached.
var autoEvent = new AutoResetEvent(false);
var statusChecker = new StatusChecker(5);
// creates a Timer to call CheckStatus() with autoEvent as argument,
// starting with 1 second delay and calling every 2 seconds.
var stateTimer = new Timer(statusChecker.CheckStatus, autoEvent, 1000, 2000);
autoEvent.WaitOne();
i use timer,
the code is
using System;
using System.Net;
using System.Timers;
static void Main(string[] args)
{
Console.WriteLine("The system is start at {0}", DateTime.Now);
Timer t = new Timer(10000);
t.Enabled = true;
t.Elapsed += T_Elapsed;
Console.ReadKey();
}
private static void T_Elapsed(object sender, ElapsedEventArgs e)
{
//write your code
}
This is what fixed for me.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Windows.Forms;
using System.Timers;
namespace GoogleDDNS
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (username.Text == "")
{
System.Windows.MessageBox.Show("Please enter the username");
username.Focus();
return;
}
if (password.Text == "")
{
System.Windows.MessageBox.Show("Please enter the password");
password.Focus();
return;
}
if (subdomain.Text == "")
{
System.Windows.MessageBox.Show("Please enter the subdomain");
subdomain.Focus();
return;
}
var client = new WebClient { Credentials = new NetworkCredential(username.Text, password.Text) };
var response = client.DownloadString("https://domains.google.com/nic/update?hostname=" + subdomain.Text);
//MessageBox.Show(response);
responseddns.Content = response;
Properties.Settings.Default.usernamesave = username.Text;
Properties.Settings.Default.passwordsave = password.Text;
Properties.Settings.Default.subdomainsave = subdomain.Text;
//Properties.Settings.Default.intervalsave = interval.Text;
Properties.Settings.Default.Save();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
username.Text = Properties.Settings.Default.usernamesave;
password.Text = Properties.Settings.Default.passwordsave;
subdomain.Text = Properties.Settings.Default.subdomainsave;
//interval.Text = Properties.Settings.Default.intervalsave;
System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer();
MyTimer.Interval = (1 * 60 * 1000); // 45 mins
MyTimer.Tick += new EventHandler(MyTimer_Tick);
MyTimer.Start();
}
private void MyTimer_Tick(object sender, EventArgs e)
{
var client = new WebClient { Credentials = new NetworkCredential(username.Text, password.Text) };
var response = client.DownloadString("https://domains.google.com/nic/update?hostname=" + subdomain.Text);
//MessageBox.Show(response);
responseddns.Content = response;
//this.Close();
}
}
}
Have a look at this. I recall a colleague using it a while ago:
FluentScheduler - [Project Site]
Usage:
// Schedule an IJob to run at an interval
Schedule<MyJob>().ToRunNow().AndEvery(2).Minutes();
Will fulfill your need.
somwhere met this code
class Program
{
static void Main(string[] args)
{
int Interval = 5;
CancellationTokenSource cancellation = new CancellationTokenSource();
Console.WriteLine("Start Loop...");
RepeatActionEvery(() => Console.WriteLine("Hi time {0}",DateTime.Now), TimeSpan.FromMinutes(Interval), cancellation.Token).Wait();
Console.WriteLine("Finish loop!!!");
}
public static async Task RepeatActionEvery(Action action, TimeSpan interval, CancellationToken cancellationToken)
{
while (true)
{
action();
Task task = Task.Delay(interval, cancellationToken);
try
{
await task;
}
catch (TaskCanceledException)
{
return;
}
}
}
}
I managed to get into learning how to make phone apps. I'm completely new to c# and xaml. But I have done visual basic to a basic knowledge.
I am trying to recreate my project in the windows phone and I've got the basic progress bar in a timer but when the timer has reached it's end I want it to navigate to a new page which I have created. I have seen many different examples but none have helped It either doesn't work or has an error.
This is the code so far on the MainPage:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.Windows.Threading;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using ProgramOSMobile.Resources;
namespace ProgramOSMobile
{
public partial class MainPage : PhoneApplicationPage
{
private DispatcherTimer timer;
private int i, j;
public MainPage()
{
InitializeComponent();
timer = new DispatcherTimer();
timer.Tick += timer_tick;
Init();
timer.Start();
}
private void Init()
{
j = i = Convert.ToInt32(3);
timer.Interval = TimeSpan.FromMilliseconds(i);
}
private void timer_tick(object sender, EventArgs e)
{
progressBar1.Value = i;
i = i + j;
if (i == 1010)
{
timer.Stop();
}
}
}
}
This all works, but when it comes to using this code for example:
NavigationService.Navigate(new Uri("/LoginScreen.xaml", UriKind.Relative));
Or indeed this new one for the Phone 8.1:
this.Frame.Navigate(typeof(LoginScreen));
I get an error on the 'Frame' part.
Sorry for the really long question but it's just really confusing me.
Thanks,
Dan
As I can see you are using Windows Phone 8.1 Silverlight project and error you are having is used in WinRT version. Here is code for navigation after timer.
for WinRT
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var timer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(300) };
timer.Start();
timer.Tick += ((ax, by) =>
{
timer.Stop();
Loader.IsActive = false;
this.Frame.Navigate(typeof(HomePage));
});
}
and for Silverlight project which you are using
public MainPage()
{
InitializeComponent();
Loaded+=MainPage_Loaded;
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
var timer = new System.Windows.Threading.DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(2);
timer.Start();
timer.Tick += ((ax, by) => { timer.Stop();
NavigationService.Navigate(new Uri("/Source Code/Recieve.xaml", UriKind.RelativeOrAbsolute));
});
}
You are using Init method for initialization of timer and you can do it fixed I did or dynamic as you like. If any error is thrown then check exception in output it maybe because of Xaml error on next page i.e. HomePage. Hope it helps.
The following code worked for me .. Try it out
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.Windows.Threading;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using ProgramOSMobile.Resources;
namespace ProgramOSMobile
{
public partial class MainPage : PhoneApplicationPage
{
DispatcherTimer timer = new DispatcherTimer();
int tick=0;
public MainPage()
{
InitializeComponent();
timer.Interval = TimeSpan.FromSeconds(0.5);
timer.Start();
timer.Tick += new EventHandler(splash);
}
private void splash(object sender, EventArgs e)
{
tick++;
if(tick==5){
NavigationService.Navigate(new Uri("/Menu.xaml", UriKind.Relative));
}
}
}
}
The above code has a timer interval of 0.5 seconds and time tick rate of 1