我创建播放无尽的音频流的应用程序。 还有的是,我可以查询得到当前播放曲目的标题和艺术家独立的Web服务。 我想要做的就是查询服务,每20秒钟,然后设置相应的曲目名称/艺术家。 目前我使用背景AudioPlayerAgent,使流,可以在我的应用程序之外播放。 这里是我到目前为止的代码:
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的响应抛出。 这是这样做的正确方法? 有没有人有任何建议,我怎么能解决这个问题?