Hello, I've got a few side projects going and ran into a bit of a coding nightmare. I've come up with a solution, but I really don't like it and was hoping that there is a graceful way to do this in C# without resorting to what I think is a very naive solution.
I'm using OpenAL to load and play a sound file, but the code needs to deal with sound objects that might have failed at loading. An example would be as follows:
Sound mySound = SoundHandler.Instance.GetSound("audio.wav");
mySound.Position = new Vector3(100, 0, 0);
mySound.Play();
It's possible that SoundHandler may return a null object if the file audio.wav does not exist, or some other error occurred. Which, of course, would result in a NullReferenceException.
Each sound object has a IsLoaded property, which is true if the Sound object loaded properly. So what I did was I programmed SoundHandler to return a Sound object with the IsLoaded property set to false. Then I've added one line of code to the start of every Sound method.
example:
/// <summary>
/// Plays the sound source.
/// </summary>
public void Play()
{
if (!IsLoaded) return;
Al.alSourcePlay(s_source[0]);
}
/// <summary>
/// Stops the sound source.
/// </summary>
public void Stop()
{
if (!IsLoaded) return;
Al.alSourceStop(s_source[0]);
}
/// <summary>
/// Pauses the sound source.
/// </summary>
public void Pause()
{
if (!IsLoaded) return;
Al.alSourcePause(s_source[0]);
}
Is there a neater way to do this? I was thinking about using delegates with the names Play, Pause, Stop, etc and then pointing them at an empty method in the Sound constructor if the audio fails to load... but I'm not sure if that's the best way. Suggestions? Thanks,
Giawa