I'm creating an app that plays an endless audio stream. There is a separate web service that I can query to get the title and artist of the currently playing track. What I want to do is query that service every 20 seconds and then set the track title/artist accordingly. Currently I'm using a background AudioPlayerAgent so that the stream can be played outside of my application. Here is the code I have so far:
public AudioPlayer()
{
if (!_classInitialized)
{
_classInitialized = true;
// Subscribe to the managed exception handler
Deployment.Current.Dispatcher.BeginInvoke(delegate
{
Application.Current.UnhandledException += AudioPlayer_UnhandledException;
});
trackTimer = new Timer(TrackTimerTick, null, 1000, 5000);
}
}
public void TrackTimerTick(object state) {
// Create a HttpWebrequest object to the desired URL.
HttpWebRequest trackRequest = (HttpWebRequest)HttpWebRequest.Create("<stream url>");
// Start the asynchronous request.
IAsyncResult result = (IAsyncResult)trackRequest.BeginGetResponse(new AsyncCallback(TrackCallback), trackRequest);
}
public void TrackCallback(IAsyncResult result) {
if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing && result != null) {
try {
// State of request is asynchronous.
HttpWebRequest trackRequest = (HttpWebRequest)result.AsyncState;
HttpWebResponse trackResponse = (HttpWebResponse)trackRequest.EndGetResponse(result);
using (StreamReader httpwebStreamReader = new StreamReader(trackResponse.GetResponseStream())) {
string results = httpwebStreamReader.ReadToEnd();
StringReader str = new StringReader(results);
XDocument trackXml = XDocument.Load(str);
string title = (from t in trackXml.Descendants("channel") select t.Element("title").Value).First<string>();
string artist = (from t in trackXml.Descendants("channel") select t.Element("artist").Value).First<string>();
if (BackgroundAudioPlayer.Instance.Track != null) {
AudioTrack track = BackgroundAudioPlayer.Instance.Track;
track.BeginEdit();
track.Title = title;
track.Artist = artist;
track.EndEdit();
}
}
trackResponse.Close();
NotifyComplete();
} catch (WebException e) {
Debug.WriteLine(e);
Debug.WriteLine(e.Response);
} catch (Exception e) {
Debug.WriteLine(e);
}
}
}
A web exception is thrown anytime that I try to read the response from the HttpWebRequest. Is this the right way to do this? Does anyone have suggestions as to how I can fix this?