问题
- How can I convert an audio file to byte[] and play it using Naudio? (code will be appreciated)
Also related to question above, how to play audio file in Resource using Naudio? For the second question I have this code:
IWavePlayer waveOutDevice; IWaveProvider provider; public void PlaySound(byte[] sound) { waveoutDevice = new WaveOutEvent(); provider = new RawSourceWaveStrem(new MemoryStream(sound), new WaveFormat(); if (waveOutDevice != null) waveOutDevice.Stop(); waveOutDevice.Init(provider); waveOutDevice.Play(); }
In my form constructor I then do something like -
PlaySound(Properties.Resources.beepsound)
beepsound being the sound file....but I just hear a noise when this method is called. What could be wrong?
回答1:
The WaveFileReader
class can accept a Stream
as a parameter, so you can use a MemoryStream
to encapsulate a byte[]
buffer whose contents you have loaded from a file.
Something like this:
byte[] fileContent = File.ReadAllBytes(@"C:\Some\File.wav");
var waveFileReader = new WaveFileReader(new MemoryStream(fileContent), true);
You can use GetManifestResourceStream
or similar to get a stream for a resource and use that. If you want to reuse the streams, pass false
as the second parameter which will stop them being disposed along with the WaveFileReader
instance.
来源:https://stackoverflow.com/questions/33954614/playing-byte-using-naudio