问题
I need to find a way to get the length of a WMA file without using any of the Windows Media Player(WMP) dlls. I found way to do it using WMP dlls, which you can see here, but due to another issue, I'd rather find a way where I don't have to use WMP.
One promising method that use NAudio and works with MP3s can be seen below:
double GetMediaDuration(string MediaFilename)
{
double duration = 0.0;
using (FileStream fs = File.OpenRead(MediaFilename))
{
Mp3Frame frame = Mp3Frame.LoadFromStream(fs);
if (frame != null)
{
_sampleFrequency = (uint)frame.SampleRate;
}
while (frame != null)
{
if (frame.ChannelMode == ChannelMode.Mono)
{
duration += (double)frame.SampleCount * 2.0 / (double)frame.SampleRate;
}
else
{
duration += (double)frame.SampleCount * 4.0 / (double)frame.SampleRate;
}
frame = Mp3Frame.LoadFromStream(fs);
}
}
return duration;
}
Does anyone know of a way to port this over to work with a WMA file instead?
I looked at the source for the WindowsMediaFormat project, but I could not find a WMAFrame class or anything that might obviously let me swap out a class in order to get this working for WMAs.
回答1:
You won't need NAudio for this one, but Windows Media.NET ( http://windowsmedianet.sourceforge.net/ )
You will open MediaReader, and retrieve so called 'samples' that are compressed audio packages. Each of them should have its duration. Traverse the whole file, total the duration of each package, and here is your solution.
I'll get some code if I find time for it.
More info:
Reader: http://msdn.microsoft.com/en-us/library/dd757425(v=vs.85).aspx
Callback for uncompressed samples: http://msdn.microsoft.com/en-us/library/dd743503(v=vs.85).aspx
I hope that you'll be able to put it all together!
One problem though, and that is one that drives my friend nuts - regardless of how much actual PCM is compressed in WMA file, last compressed sample that you get will always be 'padded' to full frame length, so if you want actual length that was given before compression, you can forget it.
回答2:
You can use MediaFoundationReader
and ask for its TotalDuration
property. MediaFoundationReader
is new to NAudio 1.7 and available in a preview release on NuGet. The length is calculated using the MF_PD_DURATION Media Foundation presentation attribute.
来源:https://stackoverflow.com/questions/16107774/possible-to-get-the-length-of-a-wma-file-without-using-windows-media-player