I am trying to play audio only if it isn't already playing.
I use this method in my class :
private MediaPlayer mediaPlayer;
public bool HasAudio(){
return mediaPlayer.HasAudio; // this returns null and it says property is readonly
}
Sound game = new Sound();
if (game.HasAudio() == false)//play sound
How do I get true or false value?
I think I get what's going on here.
Here, you're instantiating the Sound
, and then calling HasAudio
on it. At this point, it's trying to access its m_mediaPlayer
field but it is null because you're only instantiating it in the Play
method. As I suggested in my sidenote comment, you need to first instantiate the MediaPlayer
either in the constructor or in the field declaration.
internal class Sound
{
public bool HasAudio { get { return mediaPlayer.HasAudio; } }
private MediaPlayer mediaPlayer = new MediaPlayer();
public void Play(string fileName)
{
mediaPlayer.Open(new Uri(@"sounds/" + fileName, UriKind.RelativeOrAbsoute));
mediaPlayer.Play();
}
public void Stop()
{
mediaPlayer.Stop();
}
}