Search code examples
c#taglibtaglib-sharp

taglib-sharp: Retrieving the ChannelMode of an MP3 File


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.


Solution

  • 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)
        ...