日期:2014-01-22  浏览次数:20422 次


本来想写点进度控制与音量调整的代码的,后来发现还是太简单了,就是几个MCI命令,来回搬弄,自己都没兴趣写下去。所以我想还是写些独门一点的:音乐信息的读取!

目前常见的主流音乐格式就两种,MP3与WMA,它们都有在文件中保存音乐信息的特定格式,MP3使用的当然是家喻户晓的ID3格式,分为V1与V2两个版本;WMA是MS的宠儿,它只是ASF格式的一个分支,当然遵循ASF的包装规则。

怎么获取它们包含的音乐信息呢?一般是自己读取,当然XP系统开始提供了音乐文件的详细信息资料,利用FSO可以真接从系统那里读取到,这不在本文范围,毕竟不用控件更自由,通用性更好。所以,有必要去深入一下这几种音乐信息格式。还是用代码说话吧,先说说MP3的ID3V1与ID3V2的格式。

ID3V1很简单,共128个字节,写在文件尾部,格式如下:

Private Type Mp3ID3V1
    Header As String * 3
    Title As String * 30
    Artist As String * 30
    Album As String * 30
    Year As String * 4
    Comment As String * 30
    Genre As String * 1
End Type

ID3V2是后来出现的,可扩展性很强,写在文件头部,采用标签组格式,分两部分,一是标签组的总头部,一是每个子标签的头部,分别定义如下:

Private Type Mp3ID3V2
    Header As String * 3
    Ver As Byte
    Revision As Byte
    Flag As Byte
    Size(3) As Byte
End Type

Private Type Mp3ID3V2Tag
    Tag As String * 4
    Size(3) As Byte
    Flag(1) As Byte
End Type

为了组织音乐信息的方便,我还定义了一个自己的结构,以便于使用:

'音乐类型
Private Enum MediaType
    mciMIDI = 1
    mciMP3 = 2
    mciASF = 4
    mciVIDEO = 8
    mciWAVE = 16
End Enum
'装载音乐信息的结构
Private Type MusicInfo
    FileName As String
    MusicType As MediaType
    Title As String
    Artist As String
    Album As String
    Year As String
    Lyrics As String
    Writer As String
    Composer As String
    Bits As String
    Sample As String
    Length As Long
End Type

'我习惯于用代码说明问题,所以还是看看代码吧

Private Function GetMusicInfo(udtInfo As MusicInfo) As Boolean
    Dim strFileName As String, a() As String, i As Long
    With udtInfo
        strFileName = Dir(.FileName, vbNormal Or vbHidden Or vbReadOnly Or vbSystem Or vbArchive)
        If strFileName = vbNullString Then Exit Function
        .MusicType = GetMCIType(strFileName)
        If .MusicType And mciMP3 Then
            GetMusicInfo = GetMP3Info(udtInfo)
        ElseIf .MusicType And mciASF Then
            GetMusicInfo = GetASFInfo(udtInfo)
        End If
    End With
End Function

Private Function GetMCIType(strFileName As String) As MediaType
    Dim ext As String
    If strFileName <> vbNullString Then
        ext = LCase$(Mid$(strFileName, InStrRev(strFileName, ".")))
        Select Case ext
            Case ".mpg", ".mpeg", ".avi", ".mpe", ".mpa", ".m1v", ".ifo", ".vob"
                GetMCIType = mciVIDEO
            Case ".mp3"
                GetMCIType = mciMP3