This project has moved. For the latest updates, please go here.

Reading past unexpected Mp3Frames

Jun 15, 2010 at 3:25 AM

First, thanks for the hard work on this library.

I don't know if this was the best way to solve this problem, but I was having some issues with playing various MP3 files using the latest NAudio from the source repository.  Many files in my collection appear to have duplicate ID3v1 tags (some from Amazon MP3) at the end of the file which caused an "Not a recognised MP3 block" format exception from the Mp3Frame class.  Also some of my MP3's have some other junk after the last frame before the ID3v1 tag (saw it with a hex editor) and possibly at other places in the file.

I read here something that made me think you could sync on the 11 (eleven) 1 bits of the first 2 bytes of the MP3 Frame, so I added a quick change to the ReadNextFrame method from Mp3FileReader code to this:

public Mp3Frame ReadNextFrame(bool readData)

	byte[] header = new byte[2];
	while (mp3Stream.Read(header, 0, 2) == 2)

		if (header[0] == 0xFF && ((header[1] & 0xE0) == 0xE0))
			//move the pointer back to the beginning of the header
			//and return the Mp3Frame
			mp3Stream.Position -= 2;
			return new Mp3Frame(mp3Stream, readData);


	return null;

I suppose this could cause a problem if some junk in the file matches my header check and causes a strange or invalid MP3Frame to be created. I guess another way would be just assuming we've got all the file we can read

and adjusting the stream length to reflect that.


This seems to solve my problem.  Any thoughts?