I'm trying to read id3 tags from a directory and I found some code online i've been trying to understand.
I understand most of it except the method GetTag()
, it creates a new instance and returns an object but i can't access it from my main program.
public class Mp3Reader
{
private string _fileName;
private Stream _stream;
private byte[] data;
private const int SIZE = 128;
public Mp3Reader(string fileName)
{
_fileName = fileName;
_stream = new FileStream(_fileName, FileMode.Open, FileAccess.Read);
}
public Mp3Tag GetTag()
{
Mp3Tag tag = new Mp3Tag();
data = new byte[SIZE];
_stream.Seek(-128, SeekOrigin.End);
_stream.Read(data, 0, SIZE);
//_stream.Close();
byte b1 = data[0];
byte b2 = data[1];
byte b3 = data[2];
if ((Convert.ToChar(b1) != 'T') || (Convert.ToChar(b2) != 'A') || (Convert.ToChar(b3) != 'G'))
{
throw new Exception("This File is NOT a MP3 file with ID3 v1");
}
for (int i = 3; i < 33; i )
{
if (data[i] != 0)
tag.Title = Convert.ToChar(data[i]);
}
for (int i = 33; i < 63; i )
{
if (data[i] != 0)
tag.Artist = Convert.ToChar(data[i]);
}
for (int i = 63; i < 93; i )
{
if (data[i] != 0)
tag.Album = Convert.ToChar(data[i]);
}
for (int i = 93; i < 97; i )
{
if (data[i] != 0)
tag.Year = Convert.ToChar(data[i]);
}
for (int i = 97; i < 127; i )
{
if (data[i] != 0)
tag.Comment = Convert.ToChar(data[i]);
}
tag.Genere = data[127].ToString();
return tag;
}
}
main
static void Main(string[] args)
{
string folder = @"D:\\508-507-2209 (2017)";
var files = Directory.GetFiles(folder);
foreach(var val in files)
{
Mp3Reader tag2 = new Mp3Reader(val);
tag2.GetTag();
Console.WriteLine("");
}
}
mp3tag.cs
public class Mp3Tag
{
public string Title { get; set; }
public string Artist { get; set; }
public string Album { get; set; }
public string Year { get; set; }
public string Genere { get; set; }
public string Comment { get; set; }
}
If I manually Console.WriteLine(tag.xxx)
right above my return it'll output to the terminal fine, what I don't understand is what to do with the "tag" variable that it created. why can't i access tag.Title
in my main program?
tag.Genere = data[127].ToString();
Console.WriteLine("Title: " tag.Title);
Console.WriteLine("Artist: " tag.Artist);
Console.WriteLine("Album: " tag.Album); ;
Console.WriteLine("Year: " tag.Year);
Console.WriteLine("Comments: " tag.Comment);
Console.WriteLine("Genere" tag.Genere);
return tag;
CodePudding user response:
shouldn't this be
static void Main(string[] args)
{
string folder = @"D:\\508-507-2209 (2017)";
var files = Directory.GetFiles(folder);
foreach(var val in files)
{
Mp3Reader tag2 = new Mp3Reader(val);
Mp3Tag mp3tag = tag2.GetTag(); // <- this here
Console.WriteLine("");
}