Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read music file length in VBScript

Tags:

vbscript

I was just wondering if there was a way to get the length of an mp3 file in seconds through VBScript into a variable.

like image 840
Lugia101101 Avatar asked Dec 09 '22 11:12

Lugia101101


2 Answers

(Adapted from my answer to a similar question about JScript.)

You can use the GetDetailsOf method of the Windows Shell Folder object to get the audio file length. This technique supports all audio file types whose metadata can be read and displayed by Windows Explorer natively.

However, note that the index of the Length attribute is different on different Windows versions: it's 21 on Windows XP/2003 and 27 on Windows Vista+. See this page and this my answer for details. You will need to take this into account in your script.

Example code:

Const LENGTH = 27 ' Windows Vista+
' Const LENGTH = 21 ' Windows XP

Dim oShell  : Set oShell  = CreateObject("Shell.Application")
Dim oFolder : Set oFolder = oShell.Namespace("C:\Music")
Dim oFile   : Set oFile   = oFolder.ParseName("Track.mp3")

Dim strLength : strLength = oFolder.GetDetailsOf(oFile, LENGTH)

WScript.Echo strLength

Example output:

00:05:18

like image 74
Helen Avatar answered Feb 09 '23 01:02

Helen


Using Windows Media Player Control library is another way. Before using this make sure the path is correct.

Function MediaDuration(path)
    With CreateObject("Wmplayer.OCX")
        .settings.mute = True
        .url = path
        Do While Not .playState = 3 'wmppsPlaying
            WScript.Sleep 50
        Loop
        MediaDuration = Round(.currentMedia.duration) 'in seconds
        'MediaDuration = .currentMedia.durationString 'in hh:mm:ss format
        .Close 
    End With
End Function

WScript.Echo MediaDuration("C:\media\song.mp3")
like image 22
Kul-Tigin Avatar answered Feb 09 '23 01:02

Kul-Tigin