0

I am using the taglib-sharp library in my C# Win Forms application to retrieve the duration and bit rate of MP3 files. A code snippet follows:

TagLib.File tagFile = TagLib.File.Create(myMp3FileName);

int bitrate = tagFile.Properties.AudioBitrate;
string duration = tagFile.Properties.Duration.Hours.ToString("D2") + ":" +
                  tagFile.Properties.Duration.Minutes.ToString("D2") + ":" +
                  tagFile.Properties.Duration.Seconds.ToString("D2");

I would now like to also determine if the file is Mono or Stereo. To do that, I think I need to read the ChannelMode (0 = Stereo, 1 = JointStereo, 2 = DualChannel, 3 = SingleChannel). The only problem is that I don't know how to access it. When I debug the code, I can see ChannelMode in the watch window.

Yet accessing it is proving difficult. I only got this far:

var codec = (((TagLib.ICodec[])tagFile.Properties.Codecs).GetValue(0));

When I run this, I can see codec in the debugger's watch window, and under it is ChannelMode.

I am inclined to think that I should just be able to read codec.ChannelMode at this point, but that's clearly not the right syntax. I get this compiler error:

Error CS1061 'object' does not contain a definition for 'ChannelMode' and no extension method 'ChannelMode' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

What am I doing wrong?

Thanks in advance,

Mike.

1 Answers1

1

GetValue(0) returns a type of object. You will need to cast the return value to an appropriate type. In this case probably an AudioHeader (implements ICodec) which has a ChannelMode property. Like so

var codec = (AudioHeader)(((TagLib.ICodec[])tagFile.Properties.Codecs).GetValue(0));

Or safer

var codec = (((TagLib.ICodec[])tagFile.Properties.Codecs).GetValue(0)) as AudioHeader?;
if (codec != null)
    ...
Ben Allred
  • 4,544
  • 1
  • 19
  • 20
  • Thanks Ben! Your first solution works great! However, for what it's worth, the second solution produces a compiler error *Error CS0077 The as operator must be used with a reference type or nullable type ('AudioHeader' is a non-nullable value type)*. I'm a bit of a newb here, but is the solution that works somehow unsafe? – M. Russell Oct 26 '17 at 13:07
  • Oh, I didn't notice `AudioHeader` is a struct. The first method is fine. You just want to make sure you're casting to the right type. – Ben Allred Oct 27 '17 at 04:08
  • You can still use the second method (updated the answer) if you turn it into a `Nullable` (`... as AudioHeader?`) – Ben Allred Oct 27 '17 at 04:14