1. uVar.pas单元如下
unit uVar;
interface
uses
SysUtils, Forms;
type
TAppPara = class
public
class function AppPath: string;
class function AppName: string;
end;
TFilePath = class(TAppPara)
public
class function VoicePath: string;
end;
implementation
{ TFilePath }
class function TFilePath.VoicePath: string;
begin
Result := AppPath + 'voice\';
end;
{ TAppPara }
class function TAppPara.AppName: string;
begin
Result := ExtractFileName(Application.ExeName);
end;
class function TAppPara.AppPath: string;
begin
Result := ExtractFilePath(Application.ExeName);
end;
end.
2. uVoice.pas单元如下
unit uVoice;
interface
uses
SysUtils, MMSystem;
const
FileExt= '.wav';
type
//播放wav文件
TVoice= class
private
FFilePath: string; //wav文件目录
public
property _FilePath: string read FFilePath write FFilePath;
constructor Create(sPath: string);
destructor Destroy; override;
function Play(sFile: string): Boolean;
end;
implementation
{ TVoice }
constructor TVoice.Create(sPath: string);
begin
FFilePath:= sPath;
end;
destructor TVoice.Destroy;
begin
inherited;
end;
function TVoice.Play(sFile: string): Boolean;
var
filename: string;
begin
Result:= False;
try
filename:= FFilePath+ sFile+ FileExt;
if FileExists(filename) then
Result:= sndPlaySound(PChar(filename), SND_NODEFAULT+ SND_ASYNC);
{
SND_ASYNC 用异步方式播放声音
SND_LOOP 播放载入到内存中的声音
SND_MEMORY 播放载入到内存中的声音
SND_NODEFAULT 不播放缺省声音
SND_NOWAIT 如果驱动程序正忙则函数就不播放声音并立即返回
SND_PURGE 停止所有的声音
SND_SYNC 同步播放声音,在播放完后PlaySound函数才返回
}
finally
//
end;
end;
end.
3. uFrmMain.pas如下
unit uFrmMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OleServer, SpeechLib_TLB, StdCtrls, uVoice;
type
TFrmMain = class(TForm)
Button1: TButton;
Button2: TButton;
Label1: TLabel;
Edit1: TEdit;
SpVoice1: TSpVoice;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
FVoice: TVoice;
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
implementation
uses uVar;
{$R *.dfm}
procedure TFrmMain.Button1Click(Sender: TObject);
var
sName: string;
begin
//语音文件名
sName:= '欢迎光临';
if Assigned(FVoice) then
FVoice.Play(sName);
end;
procedure TFrmMain.Button2Click(Sender: TObject);
var
sName: string;
begin
//可能有问题
// sName:= Trim(Edit1.Text);
// SpVoice1.Speak(sName, SVSFlagsAsync);
end;
procedure TFrmMain.FormCreate(Sender: TObject);
begin
FVoice:= TVoice.Create(TFilePath.VoicePath);
end;
procedure TFrmMain.FormDestroy(Sender: TObject);
begin
FreeAndNil(FVoice);
end;
end.
4. 工程文件
program DelphiVoice;
uses
Forms,
uFrmMain in 'uFrmMain.pas' {FrmMain},
uVoice in 'uVoice.pas',
uVar in 'uVar.pas';
{$R *.res}
begin
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(TFrmMain, FrmMain);
Application.Run;
end.