我正在創建一個播放無盡音頻流的應用程序。有一個單獨的網絡服務,我可以查詢獲取當前正在播放的曲目的標題和藝術家。我想要做的是每20秒查詢一次該服務,然後相應地設置曲目標題/藝術家。目前我正在使用背景音頻播放器,以便可以在我的應用程序之外播放該流。這裏是我到目前爲止的代碼:來自AudioPlayerAgent的HttpWebRequest
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);
}
}
}
一個網絡異常隨時隨地,我嘗試讀取從HttpWebRequest的響應拋出。這是正確的方法嗎?有沒有人對我如何解決這個問題有什麼建議?
不要捕捉異常。 http://stackoverflow.com/questions/1742940/why-not-catch-general-exceptions http://msdn.microsoft.com/en-us/library/ms182137%28v=vs.100%29.aspx –
那沒有解決任何問題。 – bfink
@Sedgwickz評論似乎部分解決了這個問題,我現在可以正確地獲取曲目數據。但是,一旦我呼叫NotifyComplete(),計時器不再打勾 - 有關如何解決此問題的任何提示? – bfink