Page 1 of 1

How get the exact silence time

PostPosted: November 26th, 2008, 12:00 pm
by JARS
I need to analize a wave file to get the exact silence time before the tone signal.
I saw that changing the BufferCount and BufferLength the result time also change.
Witch is the rigth way to get this time?

Thanks in advance
Jorge

Re: How get the exact silence time

PostPosted: November 26th, 2008, 12:22 pm
by Kambiz
The get the exact time, you have to count the wave data bytes before the silence, and then pass that offset to the following function to convert it to milliseconds.

Code: Select all
function WaveOffsetToMS(const pWaveFormat: PWaveFormatEx; Offset: DWORD): DWORD;
var
  NumOfSamples: DWORD;
begin
  with pWaveFormat^ do
  begin
    if nBlockAlign > 1 then
      Offset := nBlockAlign * (Offset div nBlockAlign);
    if (wBitsPerSample > 0) and (nSamplesPerSec > 0) then
    begin
      NumOfSamples := Trunc(Offset * (wBitsPerSample / 8));
      Result := Trunc(1000 * (NumOfSamples / nSamplesPerSec));
    end
    else
      Result := Trunc(1000 * (Offset / nAvgBytesPerSec));
  end;
end;

Re: How get the exact silence time

PostPosted: November 26th, 2008, 1:48 pm
by JARS
Thanks Kambiz for your help, but how "count the wave data bytes"
I never work with audio files and I've not idea.

Re: How get the exact silence time

PostPosted: November 26th, 2008, 4:31 pm
by Kambiz
It's similar to reading a file using stream object.

Code: Select all
var
  Wave: TWaveFile;
  BytesRead: Integer;
  Buffer: array[0..1023] of Byte;
begin
  Wave := TWaveFile.Create('C:\Sample.wav', fmOpenRead or fmShareDenyWrite);
  try
    Wave.BeginRead;
    try
      BytesRead := Wave.Read(Buffer, SizeOf(Buffer));
      while BytesRead > 0 do
      begin
        // process the buffer
        BytesRead := Wave.Read(Buffer, SizeOf(Buffer));
      end;
    finally
      Wave.EndRead;
    end;
  finally
    Wave.Free;
  end;
end;


For accessing raw data you can use also TWaveStreamAdapter class, which is more generic than TWaveFile class.

However interpreting raw data may be complicated for some wave formats. Hopefully, PCM format has a straight forward definition, and makes audio processing easy.

Re: How get the exact silence time

PostPosted: November 26th, 2008, 4:39 pm
by Kambiz
I forgot to tell that if instead of TWaveFile and TWaveStreamAdapter you use TWaveStreamConverter, you can get the buffer in the format that is easier to process. In this case, before calling BeginRead, call SetBufferFormat to specify in which format the buffer should be.

And one more thing, BeginRead return false if it cannot convert the buffer to the specified format.