2008-11-07 如何取得MP3多媒體檔案播放長度 9544 0 VB.Net / C#.Net / 摘要:如何取得MP3多媒體檔案播放長度 如何取得MP3等多媒體檔案格式播放長度 << VB.Net >> Imports System.IO Imports Microsoft.Win32 ' API 宣告 Private Declare Function mciSendStringA Lib "Winmm.dll" _ (ByVal lpszCommand As String, ByVal lpszReturnString As String, _ ByVal cchReturn As Integer, ByVal hwndCallback As IntPtr) As Integer Private Sub Button1_Click(ByVal s As Object, ByVal e As EventArgs) Handles Button1.Click MessageBox.Show(Cvt2HMS(GetMediaLen("C:\音樂欣賞\Candy Shop.mp3"))) MessageBox.Show(Cvt2HMS(GetMediaLen("C:\音樂欣賞\國境之南.wmv"))) MessageBox.Show(Cvt2HMS(GetMediaLen("C:\音樂欣賞\Time to say goodbye.wma"))) MessageBox.Show(Cvt2HMS(GetMediaLen("C:\音樂欣賞\寶貝.flv"))) End Sub ' 取得多媒體檔案長度 Private Function GetMediaLen(ByVal File As String) As Long Dim key As String = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\MCI Extensions" Dim RegKey As RegistryKey = Registry.LocalMachine.OpenSubKey(key) Dim FileExt As String = (Path.GetExtension(File).Replace(".", "")) Dim tp As String = RegKey.GetValue(FileExt, "MPEGVideo") RegKey.Close() Dim tm As New String(Chr(0), 128) Dim cmd As String cmd = "open """ & File & """ type " & tp & " alias Media" If mciSendStringA(cmd, vbNullString, 0, 0) = 0 Then If mciSendStringA("status Media length", tm, tm.Length, 0) = 0 Then If tm <> "" Then GetMediaLen = Convert.ToInt32(tm) \ 1000 End If mciSendStringA("close Media", vbNullString, 0, 0) End If End Function ' 轉換成時分秒 Private Function Cvt2HMS(ByVal sec As Long) As String Dim h, m, s As Integer Cvt2HMS = "" h = sec \ 3600 If h > 0 Then Cvt2HMS &= h.ToString & "時" m = (sec Mod 3600) \ 60 If m > 0 Then Cvt2HMS &= m.ToString & "分" s = (sec Mod 3600) Mod 60 If s > 0 Then Cvt2HMS &= s.ToString & "秒" End Function << C# >> using System.IO; using Microsoft.Win32; // API 宣告 [DllImport("winmm.dll", EntryPoint = "mciSendString", CharSet = CharSet.Auto)] public static extern int mciSendString( string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback); private void button1_Click(object s, EventArgs e) { MessageBox.Show(GetMediaLen(@"D:\音樂欣賞\Dirty.mp3").ToString() + " Sec"); } // 取得多媒體檔案長度 private long GetMediaLen(string File) { long RetVal = 0; string key = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\MCI Extensions"; RegistryKey RegKey = Registry.LocalMachine.OpenSubKey(key); string FileExt = Path.GetExtension(File).Replace(".", ""); string tp = RegKey.GetValue(FileExt, "MPEGVideo").ToString(); RegKey.Close(); string tm = new string((char)0, 128); if (mciSendString("open \"" + File + "\" type " + tp + " alias Media", null, 0, 0) == 0) { if (mciSendString("status Media length", tm, tm.Length, 0) == 0) { tm = tm.Trim((char)0); if (!string.IsNullOrEmpty(tm)) RetVal = Convert.ToInt64(tm) / 1000; } mciSendString("close Media", null, 0, 0); } return RetVal; } 回首頁