Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting Album art from MP3 files using TagLib - Is there a better way write this code?

I'm using Visual Basic 9 (VS2008) and TagLib.

The following code extracts the album art from an MP3 file and displays it in a PictureBox.

Is there a better way to write this code?

 Dim file As TagLib.File = TagLib.File.Create(filepath)

 If file.Tag.Pictures.Length >= 1 Then
    Dim bin As Byte() = DirectCast(file.Tag.Pictures(0).Data.Data, Byte())
    PreviewPictureBox.Image = Image.FromStream(New MemoryStream(bin)).GetThumbnailImage(100, 100, Nothing, System.IntPtr.Zero)
 End If
like image 769
user57175 Avatar asked Nov 24 '25 06:11

user57175


2 Answers

At first glance it looks okay to me.

You could add some error handling, for example if TagLib.File.Create() throws an error or returns "Nothing". Also if the Tag property is empty for some reason, an error will be thrown if you'll try to access ".Pictures".

like image 186
splattne Avatar answered Nov 26 '25 18:11

splattne


I'm not intimately familiar with TagLib but it doesn't look like there is much of a better way to write this. The only suggestion I can give is that you could reduce the amount of code by taking advantage of type inference. The two variable declarations don't need an explicit type if "Option Infer" is currently on. This doesn't actually change the quality of the code though, it just reduces the amount of it.

Example

 Option Infer On
 ...
 Dim file = TagLib.File.Create(filepath)

 If file.Tag.Pictures.Length >= 1 Then
    Dim bin = DirectCast(file.Tag.Pictures(0).Data.Data, Byte())
    PreviewPictureBox.Image = Image.FromStream(New MemoryStream(bin)).GetThumbnailImage(100, 100, Nothing, System.IntPtr.Zero)
 End If
like image 45
JaredPar Avatar answered Nov 26 '25 19:11

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!