I'm trying to play OGG file stream with NVorbis
and NAudio
, as described in the documention, I'm trying to run this code when on a Button click, but I get an exception:
System.ArgumentException: 'Could not initialize container!'
I'm targeting .Net Framework 4.5
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
using (var vorbisStream = new NAudio.Vorbis.VorbisWaveReader(@"OGG file path"))
using (var waveOut = new NAudio.Wave.WaveOutEvent())
{
waveOut.Init(vorbisStream);
waveOut.Play();
// wait here until playback stops or should stop
}
}
Two issues here:
using
statements either the WaveOutReader or WaveOut object, since the latter is playing the sound asynchronously and it needs the WaveOutReader's Stream openNAudio
andNVorbis
I assume you have already successfully installed the NAudio 2.1.0 and NAudio.Vorbis 1.5.0 packages in a new .Net 6+ Project.
You just need to add references to
NAudio.Vorbis
andNAudio.Wave
Targeting .Net 6+,
nullable
enabled.Add two Button Controls to a Form, one named
btnPlayAudio
and the otherbtnStopPlayback
, initially disabled; subscribe to their Click event using the event handlers shown here.The WaveOutReader and the WaveOut object that acts as player are declared as instance Fields, initially set to
null
.When you press the Play Audio Button, the audio Stream and the Player are initialized, calling the
WaveOutInit()
method, which also subscribes to the WaveOut object'sPlaybackStopped
event.When you call the WaveOut object's
Stop()
method or the OGG playback terminates, this event is raised. Here, theStop()
method is called in thebtnStopPlayback
click handler.When this happens, another method,
WaveOutReset()
, is called; this method disposes of the WaveOut object and the Stream of the WaveOutReader. The event handler is also removed.