简体   繁体   中英

Problems with BackgroundPlayer in WP7

I have problems with playing streaming audio in my wp7 project.

In solution i am add new BackgroundPlayer project and add reference to general project. My AudioPlayer.cs looks next:

public class AudioPlayer : AudioPlayerAgent
{
    public static List<AudioTrack> Playlist = new List<AudioTrack>();
    public static int CurrentTrackPlayed;
    private void PlayTrack(BackgroundAudioPlayer player)
    {
        player.Track = Playlist[CurrentTrackPlayed];
        player.Play();
    }
    private void PlayNext(BackgroundAudioPlayer player)
    {
        if (++CurrentTrackPlayed >= Playlist.Count)
            CurrentTrackPlayed = 0;
        PlayTrack(player);
    }
    private void PlayBack(BackgroundAudioPlayer player)
    {
        if (--CurrentTrackPlayed < 0)
            CurrentTrackPlayed = Playlist.Count - 1;
        PlayTrack(player);
    }
    private static volatile bool _classInitialized;

    public AudioPlayer()
    {
        if (_classInitialized) return;
        _classInitialized = true;
        Deployment.Current.Dispatcher.BeginInvoke(delegate
                                                      {
                                                          Application.Current.UnhandledException += AudioPlayerUnhandledException;
                                                      });
    }
    private static void AudioPlayerUnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
    {
        if (System.Diagnostics.Debugger.IsAttached)
        {
            System.Diagnostics.Debugger.Break();
        }
    }
    protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState)
    {
        switch (playState)
        {
            case PlayState.TrackEnded:
                PlayNext(player);
                break;
            case PlayState.TrackReady:
                player.Play();
                break;
            case PlayState.Shutdown:
                // TODO: обработайте здесь состояние отключения (например, сохраните состояние)
                break;
        }

        NotifyComplete();
    }
    protected override void OnUserAction(BackgroundAudioPlayer player, AudioTrack track, UserAction action, object param)
    {
        MessageBox.Show(action.ToString());
        switch (action)
        {
            case UserAction.Play:
                PlayTrack(player);
                break;
            case UserAction.Stop:
                player.Stop();
                break;
            case UserAction.Pause:
                player.Pause();
                break;
            case UserAction.FastForward:
                player.FastForward();
                break;
            case UserAction.Rewind:
                player.Rewind();
                break;
            case UserAction.Seek:
                player.Position = (TimeSpan) param;
                break;
            case UserAction.SkipNext:
                PlayNext(player);
                break;
            case UserAction.SkipPrevious:
                PlayBack(player);
                break;
        }

        NotifyComplete();
    }
    protected override void OnError(BackgroundAudioPlayer player, AudioTrack track, Exception error, bool isFatal)
    {
        if (isFatal)
        {
            Abort();
        }
        else
        {
            NotifyComplete();
        }

    }
}

in my general project, first i add new audio tracks to Playlist object:

AudioPlayer.Playlist = audios.Select(a => new AudioTrack(new Uri(a.Url, UriKind.Absolute), a.Title, a.Artist, null, null)).ToList();
                AudioPlayer.CurrentTrackPlayed = 0;

and next i am trying to play song using this code:

private void PlaySound(Audio a, Shape r)
    {
        try
        {
            if (_lastSelector != null)
                _lastSelector.Fill = Application.Current.Resources["PhoneInverseBackgroundBrush"] as SolidColorBrush;
            if (searchBox.Visibility == Visibility.Visible)
                Store.CurrentAudioIndex = _searched.IndexOf(a);
            else if (_isAudios)
                Store.CurrentAudioIndex = _audios.IndexOf(a);
            else if (_isRecommendations)
                Store.CurrentAudioIndex = _recommendations.IndexOf(a);
            BackgroundAudioPlayer.Instance.Play();
            if (r != null)
            {
                r.Fill = VKMobile.Resources.AccentBrush;
                _lastSelector = r;
            }
        }catch(Exception e)
        {
            MessageBox.Show(e.Message);
        }
    }

but it's not work, playing isnt start

whats wrong?

I did not test it but after some analyzing I would suggest at least these 2 changes:

First one is to use;

 AudioPlayer.Playlist.AddRange( .... ); //no ToList() copy needed.

Second one is the source of your error i think, the Singleton Backgroundplayer Track is not set after you added the new AudioTracks to the playlist.

try adding something like this:

player.Track = Playlist[CurrentTrackPlayed];

I would suggest some other changes, like dropping the BackgroundPlayer player parameter in your control methods.

It is a Singleton so there is only and just 1 instance of it. Hence the static property name Instance.

You can use it fairly simple throughout your AudioPlayer class an Example with your wanted functionality a little bit more encapsulated:

public static void AddAndPlayTrack(AudioTrack trackToPlay)
    {
        BackgroundAudioPlayer.Instance.Track = trackToPlay;
        Playlist.Add(trackToPlay);
        CurrentTrackPlayed = Playlist.LastIndexOf(trackToPlay);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM