如何在不使用TMediaPlayer打开文件的情况下获取Wav文件的长度?
使用MCI_SENDSTRING API调用可以获取长度,但这确实涉及到。但是,已经提出了一种更好的方法,可以直接访问文件并解释其自身的内部数据以获得信息。
这是函数:
function GetWaveLength(WaveFile: string): Double;
var
groupID: array[0..3] of char;
riffType: array[0..3] of char;
BytesPerSec: Integer;
Stream: TFileStream;
dataSize: Integer;
// chunk seeking function,
// -1 means: chunk not found
function GotoChunk(ID: string): Integer;
var
chunkID: array[0..3] of char;
chunkSize: Integer;
begin
Result := -1;
with Stream do
begin
// index of first chunk
Position := 12;
repeat
// read next chunk
Read(chunkID, 4);
Read(chunkSize, 4);
if chunkID <> ID then
// skip chunk
Position := Position + chunkSize;
until (chunkID = ID) or (Position >= Size);
if chunkID = ID then
// chunk found,
// return chunk size
Result := chunkSize;
end;
end;
begin
Result := -1;
Stream := TFileStream.Create(WaveFile, fmOpenRead or fmShareDenyNone);
with Stream do
try
Read(groupID, 4);
Position := Position + 4; // skip four bytes (file size)
Read(riffType, 4);
if (groupID = 'RIFF') and (riffType = 'WAVE') then
begin
// search for format chunk
if GotoChunk('fmt') <> -1 then
begin
// found it
Position := Position + 8;
Read(BytesPerSec,4);
//search for data chunk
dataSize := GotoChunk('data');
if dataSize <> -1 then
// found it
Result := dataSize / BytesPerSec
end
end
finally
Free;
end;
end;
This returns the number of seconds as a floating point number, which is not necessarily the most helpful format. Far better to return it as a string representing the time in hours, minutes and seconds. The following function achieves this based on the number of seconds as an integer:
function SecondsToTimeStr(RemainingSeconds: Integer):String;
var
Hours, Minutes, Seconds: Integer;
HourString, MinuteString, SecondString: String;
begin
// Calculate Minutes
Seconds := RemainingSeconds mod 60;
Minutes := RemainingSeconds div 60;
Hours := Minutes div 60;
Minutes := Minutes-(Hours*60);
if Hours < 10 then
HourString := '0'+IntToStr(Hours)+':'
else
HourString := IntToStr(Hours)+':';
if Minutes < 10 then
MinuteString := '0'+ IntToStr(Minutes)+':'
else
MinuteString := IntToStr(Minutes)+':';
if Seconds <10 then
SecondString := '0'+ IntToStr(Seconds)
else
SecondString := IntToStr(Seconds);
Result := HourString+MinuteString+SecondString;
end;
这将返回秒数作为浮点数,这不一定是最有用的格式。最好以字符串形式返回它,以小时,分钟和秒为单位。以下函数基于秒数(整数)实现此目的:
procedure TForm1.Button1Click(Sender: TObject);
var
Seconds: Integer;
begin
Seconds := Trunc(GetWaveLength(Edit1.Text));//gets only the Integer part of the length
Label1.Caption := SecondsToTimeStr(Seconds);
end;
创建完这些功能后,您可以从任何相关事件中调用它们,例如单击按钮:
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Caption := SecondsToTimeStr(Trunc(GetWaveLength(Edit1.Text)));
end;
Copyright © 2014 DelphiW.com 开发 源码 文档 技巧 All Rights Reserved
晋ICP备14006235号-8 晋公网安备 14108102000087号
执行时间: 0.033324003219604 seconds