I have a procedure that opens an encrypted mp3, decrypts it to a memory stream, and then uses NAudio to play it. The encrypted mp3 file plays okay, but then the app locks.
I'm new to NAudio, and this is the first app I'm working on. Here's the code I've got.
public void PlayEncMP3(String sourceFile)
{
FileInfo info = new FileInfo(sourceFile);
FileStream input = new FileStream(sourceFile, FileMode.Open, FileAccess.Read);
DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
cryptic.Key = ASCIIEncoding.ASCII.GetBytes("64BITKEY");
cryptic.IV = ASCIIEncoding.ASCII.GetBytes("64BIT_IV");
CryptoStream crStream = new CryptoStream(input, cryptic.CreateDecryptor(), CryptoStreamMode.Read);
BinaryReader rdr = new BinaryReader(crStream);
byte[] dta = new byte[info.Length];
rdr.Read(dta, 0, (int)info.Length);
Stream stream = new MemoryStream(dta);
using (WaveStream waveStream = new Mp3FileReader(stream))
{
using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
{
waveOut.Init(waveStream);
waveOut.Play();
while (waveOut.PlaybackState == PlaybackState.Playing)
{
System.Threading.Thread.Sleep(100);
}
waveOut.Stop();
}
}
}
What seems to be happening is that the waveOut.PlaybackState is never being set to stopped. Debug statements show that loop lasting for as long as I care to wait, but the length of the mp3 file is only 5 seconds. Any idea why this is happening?
Removing that while loop on the PlaybackState has the result that the mp3 file does not play at all.
I tried simplifying the play code as follows, but with THIS version the mp3 file never plays. (Got this "solution" from this link: How to play a MP3 file using NAudio)
public void PlayEncMP3(String sourceFile)
{
// Get the encrypted file and setup the decryption engine
FileInfo info = new FileInfo(sourceFile);
FileStream input = new FileStream(sourceFile, FileMode.Open, FileAccess.Read);
DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
cryptic.Key = ASCIIEncoding.ASCII.GetBytes("64BITKEY");
cryptic.IV = ASCIIEncoding.ASCII.GetBytes("64BIT_IV");
// Implement the decryptor
CryptoStream crStream = new CryptoStream(input, cryptic.CreateDecryptor(), CryptoStreamMode.Read);
// Read the decrypted file into memory and convert to a memory stream
BinaryReader rdr = new BinaryReader(crStream);
byte[] dta = new byte[info.Length];
rdr.Read(dta, 0, (int)info.Length);
Stream stream = new MemoryStream(dta);
// Open the waveStream for NAudio
using (WaveStream waveStream = new Mp3FileReader(stream))
{
// Open the waveOut
using (WaveOut waveOut = new WaveOut())
{
// Play the file
waveOut.Init(waveStream);
waveOut.Play();
}
}
}
BTW, I have two sound files I'm testing with (the second is 6 seconds long), and both behave the same way. Both sound files played perfectly okay when I was using the .NET SoundPlayer.
I am using the latest version of NAudio... downloaded it from the site this morning.
Any ideas how to fix this?