I have two pages say Page1 and page2. In Page-1 I have a listview and an Image button(tap gesture). Here if I click listview item, it navigates to Page2 where it plays a song.
Navigation.PushModalAsync(new page2(parameter1));
Song continues to play. Then I go back to page1 by clicking back button. Then as mentioned I have an imagebutton in page1, if I click this image button, I want to go the same page which was shown earlier(page2) with same status song continues to play (it should not play from the beginning).
I understand, if I click the back button, it destroys the model page. For some reason, I can't use pushasync(). Is this possible?
Would recommend not to tightly couple your audio/media player logic with your navigation logic or Page objects - especially if you want it to continue playing in the background.
Simplest approach would be to have a AudioPlayerService class that subscribes to MessengingCenter for audio player commands - such as play, pause etc. When a play command is published, it can initiate a background thread to play the audio file.
MessagingCenter.Subscribe<Page2, AudioPlayerArgs> (this, "Play", (sender, args) => {
// initiate thread to play song
});
Now, when you navigate from page1 to page2, you can publish/send a command to the AudioPlayerService class through MessengingCenter to start playing the song. This way, any number of back-and-forth between page1 or page2 won't affect the audio player as it can ignore the play commands if it is already playing the same audio file.
MessagingCenter.Send<Page2, AudioPlayerArgs> (this, "Play", new AudioPlayerArgs("<sound file path>"));
Note: I personally avoid using MessengingCenter in my code - A better approach would be to rather introduce an interface for IAudioPlayerService with appropriate methods to play, pause etc. and use DependencyService to maintain the AudioPlayerService state as a global object (which is default behavior)
public interface IAudioPlayerService {
bool PlayAudio(string file);
bool PauseAudio();
bool StopAudio();
}
[assembly: Xamarin.Forms.Dependency (typeof (IAudioPlayerService))]
public class AudioPlayerService : IAudioPlayerService {
//implement your methods
}
And, use following code to control your audio player service in your Page/ViewModel objects.
DependencyService.Get<IAudioPlayerService>().Play("<sound file path>");
You may try to pass the same instance of a global or local variable, whatever is appropriate:
var secondpage = new page2(parameter1); // Global scope.
...
Navigation.PushModalAsync(secondpage);
Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With