随笔 - 2146  文章 - 97 评论 - 11767 trackbacks - 253


TMediaPlayer 录音是基于一个已存在的 wav 文件, 上次建立空白 wav 的函数可派上用场了.

TMediaPlayer 的功能是基于 MCI 的, 都是该淘汰的东西了, 只是简单了解下.

接下来还要学习用 waveIn...系列函数录音、用 DirectSound 录音.

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, MPlayer, StdCtrls;

type
  TForm1 = class(TForm)
    MediaPlayer1: TMediaPlayer;
    Button1: TButton;
    Button2: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses MMSystem;

//建立一个空白 Wave 文件的函数
function CreateWav(chan, freq, bit: Word; const FilePath: string): Boolean;
var
  h: HMMIO;
  ckiRiff, ckiFmt, ckiData: TMMCKInfo;
  fmt: TPCMWaveFormat;
begin
  ZeroMemory(@ckiRiff, SizeOf(TMMCKInfo));
  ckiRiff.cksize := 36;
  ckiRiff.fccType := mmioStringToFOURCC('WAVE', 0);

  ZeroMemory(@ckiFmt, SizeOf(TMMCKInfo));
  ckiFmt.ckid := mmioStringToFOURCC('fmt', 0);

  ZeroMemory(@ckiData, SizeOf(TMMCKInfo));
  ckiData.ckid := mmioStringToFOURCC('data', 0);

  fmt.wf.wFormatTag := WAVE_FORMAT_PCM;
  fmt.wf.nChannels := chan;
  fmt.wf.nSamplesPerSec := freq;
  fmt.wf.nAvgBytesPerSec := freq * chan * bit div 8;
  fmt.wf.nBlockAlign := chan * bit div 8;
  fmt.wBitsPerSample := bit;

  h := mmioOpen(PChar(FilePath), nil, MMIO_CREATE or MMIO_WRITE);
  if h = 0 then Exit(False);

  if (mmioCreateChunk(h, @ckiRiff, MMIO_CREATERIFF) = MMSYSERR_NOERROR) and
    (mmioCreateChunk(h, @ckiFmt, 0) = MMSYSERR_NOERROR) and
    (mmioWrite(h, PAnsiChar(@fmt), SizeOf(TPCMWaveFormat)) = SizeOf(TPCMWaveFormat)) and
    (mmioAscend(h, @ckiFmt, 0) = MMSYSERR_NOERROR) and
    (mmioCreateChunk(h, @ckiData, 0) = MMSYSERR_NOERROR) then Result := True;

  mmioClose(h, 0);
end;

//文件路径
const path = 'C:\Temp\Test.wav';

//开始录音
procedure TForm1.Button1Click(Sender: TObject);
begin
  CreateWav(2, 22050, 16, path);

  MediaPlayer1.FileName := path;
  MediaPlayer1.Open;
  MediaPlayer1.StartRecording;

  Button2.Enabled := True;
end;

//停止录音并播放
procedure TForm1.Button2Click(Sender: TObject);
begin
  MediaPlayer1.Stop;
  MediaPlayer1.Play;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  MediaPlayer1.Visible := False;
  Button2.Enabled := FileExists(path);
end;

end.

posted on 2009-11-10 13:48  万一  阅读(...)  评论(...编辑  收藏