2005. szeptember 8., csütörtök

Four different ways to load and play sound files


Problem/Question/Abstract:

Four different ways to load and play sound files

Answer:

There are four ways of loading and playing sound in your program:

Use the sndPlaySound() function to directly play a wave file
Read the wave file into memory, then use the sndPlaySound() to play the wave file
Use sndPlaySound to directly play a wave file thats embedded in a resource file attached to your application.
Read a wave file thats embedded in a resource file attached to your application into memory, then use the sndPlaySound() to play the wave file


Sample Code:

unit PlaySnd1;

interface

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

type
  TForm1 = class(TForm)
    PlaySndFromFile: TButton;
    PlaySndFromMemory: TButton;
    PlaySndbyLoadRes: TButton;
    PlaySndFromRes: TButton;
    procedure PlaySndFromFileClick(Sender: TObject);
    procedure PlaySndFromMemoryClick(Sender: TObject);
    procedure PlaySndFromResClick(Sender: TObject);
    procedure PlaySndbyLoadResClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}
{$R snddata.res} // Resource file containing the *.wav file

uses
  MMSystem;

{1. Use the sndPlaySound() function to directly play a wave file}

procedure TForm1.PlaySndFromFileClick(Sender: TObject);
begin
  sndPlaySound('hello.wav', SND_FILENAME or SND_SYNC);
end;

{2. Read the wave file into memory, then use the sndPlaySound() to play the wave file}

procedure TForm1.PlaySndFromMemoryClick(Sender: TObject);
var
  f: file;
  p: pointer;
  fs: integer;
begin
  AssignFile(f, 'hello.wav');
  Reset(f, 1);
  fs := FileSize(f);
  GetMem(p, fs);
  BlockRead(f, p^, fs);
  CloseFile(f);
  sndPlaySound(p, SND_MEMORY or SND_SYNC);
  FreeMem(p, fs);
end;

{3. Use sndPlaySound to directly play a wave file thats embedded in a resource file attached
to your application}

procedure TForm1.PlaySndFromResClick(Sender: TObject);
begin
  PlaySound('HELLO', hInstance, SND_RESOURCE or SND_SYNC);
end;

{4. Read a wave file thats embedded in a resource file attached to your application into memory,
then use the sndPlaySound() to play the wave file}

procedure TForm1.PlaySndbyLoadResClick(Sender: TObject);
var
  h: THandle;
  p: pointer;
begin
  h := FindResource(hInstance, 'HELLO', 'WAVE');
  h := LoadResource(hInstance, h);
  p := LockResource(h);
  sndPlaySound(p, SND_MEMORY or SND_SYNC);
  UnLockResource(h);
  FreeResource(h);
end;

end.

Nincsenek megjegyzések:

Megjegyzés küldése