用汇编吧
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
Tpcspeaker = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
procedure NoSound;
procedure Sound(Freq: Word);
procedure SetPort(address, value: Word);
function GetPort(address: Word): Word;
{ Private declarations }
public
procedure Delay(MSecs: Integer);
procedure Play(Freq: Word;
MSecs: Integer);
{ Public declarations }
end;
var
pcspeaker: Tpcspeaker;
implementation
{$R *.DFM}
procedure TPCSpeaker.NoSound;
var
wValue: Word;
begin
wValue := GetPort($61);
wValue := wValue and $FC;
SetPort($61, wValue);
end;
procedure TPCSpeaker.Sound(Freq: Word);
var
B: Word;
begin
if Freq > 18 then
begin
Freq := Word(1193181 div LongInt(Freq));
B := GetPort($61);
B := GetPort($61);
if (B and 3) = 0 then
begin
SetPort($61, B or 3);
SetPort($43, $B6);
end;
SetPort($42, Freq);
SetPort($42, (Freq SHR 8));
end;
end;
procedure TPCSpeaker.Delay(MSecs: Integer);
var
FirstTickCount : LongInt;
begin
FirstTickCount:=GetTickCount;
repeat
Application.ProcessMessages;
{allowing access to other controls,
etc.}
until ((GetTickCount-FirstTickCount) >= LongInt(MSecs));
end;
procedure TPCSpeaker.Play(Freq: Word;
MSecs: Integer);
begin
Sound(Freq);
Delay(MSecs);
//NoSound;
end;
procedure TPCSpeaker.SetPort(address, value: Word);
var
bValue: Byte;
begin
bValue := trunc(value and 255);
asm
mov DX, address
mov AL, bValue
out DX, AL
end;
end;
function TPCSpeaker.GetPort(address: Word): Word;
var
bValue: Byte;
begin
asm
mov DX, address
in AL, DX
mov bValue, AL
end;
result := bValue;
end;
procedure Tpcspeaker.Button1Click(Sender: TObject);
begin
play(1800,100);//由这两个参数控制音调
end;
procedure Tpcspeaker.Button2Click(Sender: TObject);
begin
NoSound;
end;
end.