TMediaPlayer 不僅能播放多媒體,配合 dtAutoSelect 和 StartRecording 還能錄製聲音。但它不自動寫入 WAV 文件頭,需開發者手動創建帶正確頭信息的空 WAV 文件,再讓 MediaPlayer 追加寫入音頻數據。
TWavHeader = record
rId: Longint; // 'RIFF' = $46464952
rLen: Longint; // 文件總長 - 8 (此處佔位 36,實際錄製後需更新)
wId: Longint; // 'WAVE' = $45564157
fId: Longint; // 'fmt ' = $20746D66
fLen: Longint; // fmt 塊長度 = 16 (PCM)
wFormatTag: Word; // 1 = PCM
nChannels: Word; // 1=單聲道, 2=立體聲
nSamplesPerSec: Longint; // 採樣率: 11025, 22050, 44100
nAvgBytesPerSec: Longint; // nChannels * nSamplesPerSec * (wBitsPerSample/8)
nBlockAlign: Word; // nChannels * (wBitsPerSample/8)
wBitsPerSample: Word; // 8 或 16
dId: Longint; // 'data' = $61746164
wSampleLength: Longint; // 數據塊長度 (錄製前為 0)
end;
procedure TForm1.CreateWav(channels, resolution: Word; rate: Longint; 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; // 數據長度錄製後由 MediaPlayer 更新
AssignFile(wf, fn); Rewrite(wf); Write(wf, wh); CloseFile(wf);
end;
MediaPlayer1.Visible := False (隱藏自帶控制面板)BtStart:「開始錄音」,BtStop:「停止錄音」 (初始 Enabled=False)procedure TForm1.BtStartClick(Sender: TObject);
const FileName = 'Temp.wav'; // 當前目錄
begin
try
CreateWav(1, 8, 11025, ExtractFilePath(Application.ExeName) + FileName); // 8bit/11kHz/單聲道
MediaPlayer1.DeviceType := dtAutoSelect;
MediaPlayer1.FileName := ExtractFilePath(Application.ExeName) + FileName;
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;
| 參數 | 值 | 說明 |
|---|---|---|
| Channels | 1 / 2 | 單聲道/立體聲。單聲道文件體積減半。 |
| Resolution | 8 / 16 | 位深。8 位動態範圍小,16 位接近 CD 質量。 |
| Rate | 11025 / 22050 / 44100 | 採樣率。越高保真度越好,文件越大。語音 11025 足夠。 |
示例:CreateWav(1, 8, 11025, 'C:\abc.wav') → 約 11 KB/秒;CreateWav(2, 16, 44100, 'C:\abc.wav') → 約 172 KB/秒 (CD 質量)。
ACM (Audio Compression Manager) 或第三方編碼器(如 LAME),不在 MediaPlayer 能力範圍內。僅用 TMediaPlayer 和幾十行代碼即可實現功能完整的錄音機,展示了 Delphi 封裝 Windows 多媒體 API 的強大威力。理解 WAV 文件頭結構,是進行音頻處理開發的基礎。