"Let's finish with a bit of server-side scripting. I thought it might be fun to rip my CD collection into MP3s. This would allow me to listen from anywhere on my network and to easily make compilation CDs for the car, or drag a load of files onto my iPAQ for train journeys. Having tens of thousands of MP3 files sitting across a couple of 120Mb drives in one of my servers got me to thinking about user interfaces. Wouldn't it be nice to be able to programmatically select a few tracks and display them within a Web browser environment? I haven't gone quite that far yet, but what I have managed to do is pull the ID3 header information out of my MP3 files.
Here's the code you'll need. I'll be using the ADODB functions for this, because it's probably the easiest way to read binary files from ASP scripts (VBScript-based ASP has no built-in binary read facility). First, use a METADATA directive to import the required type information at run-time. This allows you to use the relevant constant names and so on.
<!-METADATA TYPE="typelib" UUID="00000205-0000-0010-8000-OOAA006D2EA4" NAME="ADODB Type Library"
Next, create the ADODB Stream object and tell it you want to work in Binary mode:
dim objstream
set objStream = Server.Createobject("ADODB.Stream")
objStream.Type = adTypeBinary
objStream.Open
At this point, you've created an empty (zero length) binary stream. The clever bit comes next - use the LoadFromFile method to grab the data from the MP3 file, and stuff it into the stream just created:
objStreain.LoadFromFile "c:\mymp3s\vu\venus - in - furs.mp3
Now, the ID3 data is stored at the end of the MP3 file (see www.id3.org/id3v1.html for more details.) This data starts 128 bytes from the end of the file, so move the pointer in the binary stream back 128 bytes from the end:
objStream.Position = objStream.size - 128
Next, read the actual ID3 tags. First, check for the string 'Tag' which will be present in all genuine MP3 files containing ID3 tags:
strTag = BinToStr(objStream.Read(3))
if ucase(strTag) = "TAG" then
Then, if that succeeded, simply read the rest of the I D3 tag data:
strTrack BinToStr(objStream.Read(30))
strArtist = BinToStr(objStreain.Read(30))
strAlbum = BinToStr(objStream.Read(30))
strYear = BinToStr(objStream.Read(4))
strComment = BinToStr(objStream.Read(30))
end if
Finally, close the stream object and set it back to nothing:
objStream.Close
set objstream = nothing
The only other thing you'll need is the BinToStr function, which takes a binary string and converts it to ASCII:
Function BinToStr(Binary)
c = 1
p =""
L = LenB(Binary)
DO While c<=L
ch = AscB(MidB(Binary,c,1))
if (ch > 31) and (ch < 127) then
p = p & Chr(ch)
end if
c = c + 1
Loop
BinToStr = trim(p)
End Function
And there you have it."