I would recommend not tightly connecting the logic of the audio / media player with the navigation logic or page objects, especially if you want it to continue to play in the background.
The easiest approach is to have an AudioPlayerService class that subscribes to the MessengingCenter for audio player commands — for example, play, pause, etc. When a play command is published, it can initiate a background stream to play an audio file.
MessagingCenter.Subscribe<Page2, AudioPlayerArgs> (this, "Play", (sender, args) => {
// initiate thread to play song
});
, 1 2, / AudioPlayerService MessengingCenter, . , 1 . 2 , , .
MessagingCenter.Send<Page2, AudioPlayerArgs> (this, "Play", new AudioPlayerArgs("<sound file path>"));
: MessengingCenter . IAudioPlayerService , .. DependencyService AudioPlayerService ( )
public interface IAudioPlayerService {
bool PlayAudio(string file);
bool PauseAudio();
bool StopAudio();
}
[assembly: Xamarin.Forms.Dependency (typeof (IAudioPlayerService))]
public class AudioPlayerService : IAudioPlayerService {
}
Page/ViewModel.
DependencyService.Get<IAudioPlayerService>().Play("<sound file path>");