Reputation: 23
I have an existing program that uses the .NET System.Media.SoundPlayer to play a wav file from a memory stream. The reason I need to do this is because the wav files are encrypted on the disk... I decrypt them to a memory stream and feed that stream to the player. It works fine.
But I'd rather use mp3's... they are smaller. I'm exploring NAudio as a solution, but can't figure out how to play an mp3 from the crypto stream.
The code I am currently using to play the encrypted wav file is this:
public void PlayEncMP3(String 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);
MainPlayer = new SoundPlayer(crStream);
MainPlayer.Play();
}
This code works perfectly. It opens the encrypted wav file, decrypts it, and feeds the decrypted wav file as a memory stream to the player, which plays the wav file normally.
I tried this with NAudio, (with code taken from this question: Play audio from a stream using C#) but the code throws an exception saying that the cryptoStream does not support seeking, so it fails trying to create the blockAlignedStream.
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);
using (WaveStream blockAlignedStream =
new BlockAlignReductionStream(
WaveFormatConversionStream.CreatePcmStream(
new Mp3FileReader(crStream))))
{
using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
{
waveOut.Init(blockAlignedStream);
waveOut.Play();
while (waveOut.PlaybackState == PlaybackState.Playing)
{
System.Threading.Thread.Sleep(100);
}
}
}
}
Any ideas how to get this working?
Edit: I tried eliminating the block aligned stream entirely and just using the cryptoStream (instead of the blockAlignedStream) in the waveOut.Init, but it can't convert the cryptoStream to the NAudio.Wave.IWaveProvider.
Upvotes: 0
Views: 523
Reputation: 49522
you can't use Mp3FileReader without a seekable stream because it tries to build a table of contents first, and it also supports repositioning during playback. So you'd need to read the entire MP3 into a memory stream first, then give that to Mp3FileReader.
Upvotes: 0