HttpWebRequest from AudioPlayerAgent

后端 未结 2 2013
生来不讨喜
生来不讨喜 2021-01-16 16:34

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

相关标签:
2条回答
  • 2021-01-16 17:07

    This has to do with the AudioPlayer going out of scope after it begins playing the music. The AudioPlayer only lives for a fraction of time and it terminated after the call to NotifyComplete

    Take a look at my reply to this post: AudioPlayerAgent, timer and webservice

    More info: The background audio thread will "suspend" after NotifyComplete is called. The way back in is when the user changes play (OnUserAction), or when the song ends (OnPlayStateChanged). If you will continue to play, get the new info within the OnPlayStateChanged method.

    0 讨论(0)
  • 2021-01-16 17:21

    You're not closing the HttpWebResponse, which is a necessity. Also, there's an overload of XDocument.Load() that takes a Stream so you don't need to use a StreamReader at all.

    EDIT: Sorry, I overlooked the Close() call at the end. But the other comment still applies.

    If it doesn't solve the problem, atleast it makes your code look cleaner:

    public void TrackCallback(IAsyncResult result) {
        if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing && result != null) {
            try {
                // State of request is asynchronous.
                HttpWebRequest trackRequest = (HttpWebRequest)result.AsyncState;
                using (HttpWebResponse trackResponse = (HttpWebResponse)trackRequest.EndGetResponse(result)){
                    XDocument trackXml = XDocument.Load(trackResponse.GetResponseStream());
    
                    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();
                    }
                }
                }
                NotifyComplete();
            } catch (WebException e) {
                Debug.WriteLine(e);
                Debug.WriteLine(e.Response);
            } catch (Exception e) {
                Debug.WriteLine(e);
            }
        }  
    }
    
    0 讨论(0)
提交回复
热议问题