How to stop music started via SndPlaySound

十年热恋 提交于 2019-12-10 09:43:27

问题


At this Website I found how to add music into a .res file and then use it in your delphi .exe. Here is the code for starting the WAVE song.

procedure TForm2.FormActivate(Sender: TObject);
var
   hFind, hRes: THandle;
   Song: PChar;
 begin
  hFind := FindResource(HInstance, 'SonicSong', 'WAVE') ;
  if hFind <> 0 then begin
    hRes:=LoadResource(HInstance, hFind) ;
    if hRes <> 0 then begin
      Song:=LockResource(hRes) ;
      if Assigned(Song) then SndPlaySound(Song, snd_ASync or snd_Memory) ;
      UnlockResource(hRes) ;
    end;
    FreeResource(hFind) ;
  end;
end;

So what I would like to know is how do I stop the music when I want to without closing the application?


回答1:


Call the sndPlaySound function with the first parameter set to nil, which causes the currently playing sound to stop. As the second parameter use the SND_ASYNC flag, because as the reference says, you must use this flag to terminate an asynchronously played waveform sound, which you are playing in your code:

sndPlaySound(nil, SND_ASYNC);



回答2:


You can simplify your code by using the SND_RESOURCE feature of PlaySound() instead of sndPlaySound():

procedure TForm2.FormActivate(Sender: TObject);
begin
  PlaySound('SonicSong', HInstance, SND_AYNC or SND_RESOURCE);
end;

procedure TForm2.FormDeactivate(Sender: TObject);
begin
  PlaySound(nil, HInstance, SND_AYNC or SND_RESOURCE);
end;



回答3:


test with:

PlaySound(nil, 0, 0);


来源:https://stackoverflow.com/questions/13123587/how-to-stop-music-started-via-sndplaysound

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!