本程序在Pwin98+Delphi5下通過。
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, MPlayer;
type
TWavHeader = record //定義一個Wav文件頭格式
rId : longint;
rLen : longint;
wId : longint;
fId : longint;
fLen : longint;
wFormatTag : Word;
nChannels : Word;
nSamplesPerSec : longint;
nAvgBytesPerSec : longint;
nBlockAlign : Word;
wBitsPerSample : Word;
dId : longint;
wSampleLength : longint;
end;
TForm1 = class(TForm)
MediaPlayer1: TMediaPlayer;
BtStart: TButton;
BtStop: TButton;
procedure CreateWav(channels : word; resolution : Word; rate : longint; fn : string);//自定義寫一個Wav文件頭過程
procedure BtStartClick(Sender: TObject);
procedure BtStopClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.CreateWav( channels : Word; { 1(單聲)或者2(立體聲) }
resolution : Word; { 8或者16,代表8位或16位聲音 }
rate : longint; { 聲音頻率,如11025,22050, 44100}
fn : string { 對應的文件名稱 } );
var
wf : file of TWavHeader;
wh : TWavHeader;
begin
wh.rId := $46464952;
wh.rLen := 36;
wh.wId := $45564157;
wh.fId := $20746d66;
wh.fLen := 16;
wh.wFormatTag := 1;
wh.nChannels := channels;
wh.nSamplesPerSec := rate;
wh.nAvgBytesPerSec := channels*rate*(resolution div 8);
wh.nBlockAlign := channels*(resolution div 8);
wh.wBitsPerSample := resolution;
wh.dId := $61746164;
wh.wSampleLength := 0;
assignfile(wf,fn); {打開對應文件 }
rewrite(wf); {移動指針到文件頭}
write(wf,wh); {寫進文件頭 }
closefile(wf); {關閉文件 }
end;
procedure TForm1.BtStartClick(Sender: TObject);
begin
try
//在程序當前目錄下創建一個Wav文件Temp.wav
CreateWav(1, 8, 11025, (ExtractFilePath(Application.ExeName)+ 'Temp.wav'));
MediaPlayer1.DeviceType := dtAutoSelect;
MediaPlayer1.FileName := (ExtractFilePath(Application.ExeName)+ 'Temp.wav');
MediaPlayer1.Open;
MediaPlayer1.StartRecording;
BtStart.Enabled:=false;
BtStop.Enabled:=true;
except
BtStart.Enabled:=True;
BtStop.Enabled:=false;
Application.MessageBox('媒體設備初始化失敗!','錯誤',MB_ICONERROR+MB_OK);
end;
end;
procedure TForm1.BtStopClick(Sender: TObject);
begin
try
MediaPlayer1.Stop;
MediaPlayer1.Save;
MediaPlayer1.Close;
Application.MessageBox('聲音錄制完畢!','信息',MB_ICONINFORMATION+MB_OK);
BtStart.Enabled:=True;
BtStop.Enabled:=false;
except
Application.MessageBox('保存聲音文件出錯!','錯誤',MB_ICONERROR+MB_OK);
BtStart.Enabled:=True;
BtStop.Enabled:=false;
end;
end;
end.
補充:1、錄制的文件播放時可能要把音頻屬性的Wav調大。
2、如果系統安裝了其它一些音頻驅動程序,則可能錄制的Wav文件大小為零,但會同時生成一個TMP結尾的文件,將其擴展名改為Wav就是錄制的聲音文件。但這種情況很少發生。(機會幾乎為零^-^)
3、本程序在運行解霸和Replayer下錄制聲音通過。