I have a Windows Forms Application where I'm trying to simply play an MP3 file from the Resource using the NAudio library.
I believe what needs to be done is to stream the file somehow, here is an example of NAudio, unfortunately it accepts File path string as an argument.
private WaveStream CreateInputStream(string fileName)
{
WaveChannel32 inputStream;
if (fileName.EndsWith(".mp3"))
{
WaveStream mp3Reader = new Mp3FileReader(fileName);
inputStream = new WaveChannel32(mp3Reader);
}
else
{
throw new InvalidOperationException("Unsupported extension");
}
volumeStream = inputStream;
return volumeStream;
}
To play the file:
waveOutDevice = new WaveOut();
mainOutputStream = CreateInputStream("C:\\song.mp3");
Works fine with normal files, how would I go about files that are located in the Resources? Thank you.
The Mp3FileReader
class can be constructed from either a filename or a System.IO.Stream
. So what you need is to read the MP3 resource as a stream. How you do that depends on how you've added the resource.
Resources added using the Properties/Resources.resx
file (managed through the application properties dialog) are accessible through the Properties.Resources
object. Known resource types (images, etc) should be represented here by their appropriate types, but MP3 files are accessed as byte[]
. You can create a MemoryStream
from the resource and use that to construct the Mp3FileReader
like so:
MemoryStream mp3file = new MemoryStream(Properties.Resources.MP3file);
Mp3FileReader mp3reader = new Mp3FileReader(mp3file);
Other resource methods differ in the details of how you get the stream, but apart from that are basically the same. If you add an MP3 file to your project with the Embedded Resource
build action, you can use the following:
public Stream GetResourceStream(string filename)
{
Assembly asm = Assembly.GetExecutingAssembly();
string resname = asm.GetName().Name + "." + filename;
return asm.GetManifestResourceStream(resname);
}
...
Stream mp3file = GetResourceStream("some file.mp3");
Mp3FileReader mp3reader = new Mp3FileReader(mp3file);
WPF resources are different again, using the pack:...
uri format and Application.GetResourceStream
.
In all cases you should, of course, dispose the Stream once you're done reading it.
Convert it to .wav using http://media.io/ then all u need to do is
(new System.Media.SoundPlayer(ProjectName.Properties.Resources.wavfilename)).Play();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With