| 1 |
{%MainUnit castlesoundengine.pas} |
| 2 |
{ |
| 3 |
Copyright 2021-2022 Michalis Kamburelis. |
| 4 |
|
| 5 |
This file is part of "Castle Game Engine". |
| 6 |
|
| 7 |
"Castle Game Engine" is free software; see the file COPYING.txt, |
| 8 |
included in this distribution, for details about the copyright. |
| 9 |
|
| 10 |
"Castle Game Engine" is distributed in the hope that it will be useful, |
| 11 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 13 |
|
| 14 |
---------------------------------------------------------------------------- |
| 15 |
} |
| 16 |
|
| 17 |
{$ifdef read_interface} |
| 18 |
|
| 19 |
//type // allow type declaration to continue |
| 20 |
|
| 21 |
{ @exclude Used with TCastleSound notifications (TCastleSound.InternalAddChangeNotification). } |
| 22 |
TSoundChange = ( |
| 23 |
{ TCastleSound.Buffer, and maybe other values, changed. } |
| 24 |
scAfterBufferCreated, |
| 25 |
{ TCastleSound.Buffer may be destroyed now, stop related sounds. } |
| 26 |
scBeforeBufferDestroyed, |
| 27 |
{ TCastleSound values, but not Buffer, changed. } |
| 28 |
scAfterOther |
| 29 |
); |
| 30 |
|
| 31 |
TCastleSound = class; |
| 32 |
|
| 33 |
{ @exclude Used with TCastleSound notifications (TCastleSound.InternalAddChangeNotification). } |
| 34 |
TCastleSoundChangeEvent = procedure (const Sender: TCastleSound; const Change: TSoundChange) of object; |
| 35 |
|
| 36 |
{ @exclude Used with TCastleSound notifications (TCastleSound.InternalAddChangeNotification). } |
| 37 |
TCastleSoundChangeEventList = class({$ifdef FPC}specialize{$endif} TList<TCastleSoundChangeEvent>) |
| 38 |
public |
| 39 |
procedure ExecuteAll(const Sender: TCastleSound; const Change: TSoundChange); |
| 40 |
end; |
| 41 |
|
| 42 |
{ Sound that can be loaded from Url (possibly reusing a cache, |
| 43 |
possibly using streaming) and played. |
| 44 |
|
| 45 |
Aside from sound file (also called "sound buffer" or "audio clip" in various APIs) |
| 46 |
this class allows to configue also playback values, like @link(Volume) and @link(Pitch). |
| 47 |
These playback values are intended to reflect preferences specific to this sound file. |
| 48 |
They are multiplied by playback values of the @link(TCastleSoundSource) |
| 49 |
(@link(TCastleSoundSource.Volume), @link(TCastleSoundSource.Pitch)) |
| 50 |
and @link(TCastlePlayingSound) (to adjust it per-playback, using |
| 51 |
@link(TCastlePlayingSound.Volume), @link(TCastlePlayingSound.Pitch)). |
| 52 |
|
| 53 |
This class does not actually play the sound. |
| 54 |
It only defines something that @italic(can) be played. |
| 55 |
To play the sound use @link(TSoundEngine.Play SoundEngine.Play) or @link(TCastleSoundSource). |
| 56 |
For spatial sounds, attach @link(TCastleSoundSource) to a @link(TCastleTransform) within some |
| 57 |
@link(TCastleViewport) and set @link(TCastleSoundSource.Sound) |
| 58 |
or call @link(TCastleSoundSource.Play). } |
| 59 |
TCastleSound = class(TCastleComponent) |
| 60 |
strict private |
| 61 |
FUrl: String; |
| 62 |
FBuffer: TInternalSoundBuffer; |
| 63 |
FStream: Boolean; |
| 64 |
FVolume: Single; |
| 65 |
FPitch: Single; |
| 66 |
FMinGain: Single; |
| 67 |
FMaxGain: Single; |
| 68 |
FPriority: Single; |
| 69 |
FReferenceDistance, FMaxDistance: Single; |
| 70 |
FChangeNotifications: TCastleSoundChangeEventList; |
| 71 |
procedure SetStream(const Value: Boolean); |
| 72 |
procedure SetUrl(const Value: String); |
| 73 |
procedure SetVolume(const Value: Single); |
| 74 |
procedure SetPitch(const Value: Single); |
| 75 |
procedure SetMinGain(const Value: Single); |
| 76 |
procedure SetMaxGain(const Value: Single); |
| 77 |
procedure SetPriority(const Value: Single); |
| 78 |
procedure SetReferenceDistance(const Value: Single); |
| 79 |
procedure SetMaxDistance(const Value: Single); |
| 80 |
procedure ReloadBuffer; |
| 81 |
procedure DoChange(const Change: TSoundChange); |
| 82 |
protected |
| 83 |
procedure Loaded; override; |
| 84 |
public |
| 85 |
const |
| 86 |
DefaultReferenceDistance = 1.0; |
| 87 |
DefaultMaxDistance = 10000.0; |
| 88 |
|
| 89 |
constructor Create(AOwner: TComponent); override; |
| 90 |
destructor Destroy; override; |
| 91 |
function PropertySections(const PropertyName: String): TPropertySections; override; |
| 92 |
|
| 93 |
{ @exclude Add notification when sound property changes. } |
| 94 |
procedure InternalAddChangeNotification(const Notify: TCastleSoundChangeEvent); |
| 95 |
{ @exclude Remove notification when sound property occurs. } |
| 96 |
procedure InternalRemoveChangeNotification(const Notify: TCastleSoundChangeEvent); |
| 97 |
|
| 98 |
{ Load sound contents from given TStream. |
| 99 |
|
| 100 |
@param(AStream Stream to load. |
| 101 |
When loading, we rewind stream positon 0 zero, |
| 102 |
and read the whole stream.) |
| 103 |
|
| 104 |
@param(MimeType Valid MIME type that indicates a sound file type, |
| 105 |
like @code(audio/wav) or @code(audio/ogg). |
| 106 |
See TUrlFile.MimeType implementation for currently supported |
| 107 |
MIME file types.) } |
| 108 |
procedure LoadFromStream(const AStream: TStream; const MimeType: String); |
| 109 |
|
| 110 |
{ Loaded sound buffer, for playing the buffer with the @link(SoundEngine). |
| 111 |
@nil if not loaded. |
| 112 |
@exclude } |
| 113 |
property InternalBuffer: TInternalSoundBuffer read FBuffer; |
| 114 |
|
| 115 |
{ Force a minimum sound loudness, despite what volume would |
| 116 |
be calculated by the spatialization. This can be used to force sound |
| 117 |
to be audible, even when it's far away from the listener. |
| 118 |
|
| 119 |
It must be in [0, 1] range. By default it is 0. } |
| 120 |
property MinGain: Single read FMinGain write SetMinGain {$ifdef FPC}default 0.0; platform { this feature is only available with OpenAL sound backend }{$endif}; |
| 121 |
|
| 122 |
{ Force a maximum sound loudness, despite what volume would |
| 123 |
be calculated by the spatialization. This can be used to limit sound volume, |
| 124 |
regardless of the distance attenuation calculation. |
| 125 |
|
| 126 |
It must be in [0, 1] range. By default it is 1. } |
| 127 |
property MaxGain: Single read FMaxGain write SetMaxGain {$ifdef FPC}default 1.0; platform { this feature is only available with OpenAL sound backend }{$endif}; |
| 128 |
|
| 129 |
{ Duration of the sound, in seconds. -1 if not loaded yet. |
| 130 |
The sound is loaded once you set @link(Url) and don't get any loading exceptions. } |
| 131 |
function Duration: Single; |
| 132 |
|
| 133 |
{ Sound data format (disregarding compression on top of it), for informational purposes. |
| 134 |
Undefined if not loaded yet. |
| 135 |
The sound is loaded once you set @link(Url) and don't get any loading exceptions. } |
| 136 |
function DataFormat: TSoundDataFormat; |
| 137 |
|
| 138 |
{ Frequency (sample rate) of the loaded sound file. |
| 139 |
0 if not loaded yet. |
| 140 |
The sound is loaded once you set @link(Url) and don't get any loading exceptions. } |
| 141 |
function Frequency: Cardinal; |
| 142 |
published |
| 143 |
{ URL of the sound file. |
| 144 |
Set this to load a new sound buffer, you can set to '' to clear the sound buffer. |
| 145 |
|
| 146 |
If you plan to change @link(Stream), note that it is best to do it before |
| 147 |
setting @link(Url). Changing @link(Stream) while @link(Url) is already set |
| 148 |
means that the sound is reloaded. } |
| 149 |
property Url: String read FUrl write SetUrl; |
| 150 |
|
| 151 |
{ Play sound using streaming. This means that the sound is gradually decompressed in memory, |
| 152 |
which means that loading time is much smaller, |
| 153 |
although there may be a small overhead on CPU during playback. |
| 154 |
Streaming is usually a good idea for longer sounds, e.g. music tracks. |
| 155 |
|
| 156 |
See also @link(TSoundLoading) for details. |
| 157 |
|
| 158 |
If you plan to change @link(Stream), note that it is best to do it before |
| 159 |
setting @link(Url). Changing @link(Stream) while @link(Url) is already set |
| 160 |
means that the sound is reloaded. } |
| 161 |
property Stream: Boolean read FStream write SetStream default false; |
| 162 |
|
| 163 |
{ Volume (how loud the sound is). |
| 164 |
|
| 165 |
Use this to indicate that e.g. a plane engine is louder than a mouse squeak |
| 166 |
(when heard from the same distance). |
| 167 |
Note: Do not make the actual sound data (in sound files) |
| 168 |
louder/more silent to express that something is louder/more silent in reality. |
| 169 |
This would usually lower the sound quality. |
| 170 |
Instead, keep your sound file data at max loudness ("normalized"), and use |
| 171 |
this property to adjust the volume associated with the sound. |
| 172 |
|
| 173 |
The effective sound volume is a multiplication of @link(TCastleSound.Volume), |
| 174 |
@link(TCastlePlayingSound.Volume) and @link(TCastleSoundSource.Volume) |
| 175 |
(if the sound is played through @link(TCastleSoundSource)). |
| 176 |
It is also affected by spatial calculations (if the sound is played |
| 177 |
through @link(TCastleSoundSource) with @link(TCastleSoundSource.Spatial) = @true) |
| 178 |
and finally by a master @link(TSoundEngine.Volume SoundEngine.Volume). |
| 179 |
|
| 180 |
Any value > 0 is allowed. The default is 1. Note that, |
| 181 |
while values > 1 are allowed, |
| 182 |
but some sound backends (like OpenAL) may clip the resulting sound volume |
| 183 |
(after all volume influences, including spatial calculations are done) to 1.0. } |
| 184 |
property Volume: Single read FVolume write SetVolume {$ifdef FPC}default 1.0{$endif}; |
| 185 |
|
| 186 |
{ Sound playing speed. |
| 187 |
|
| 188 |
The effective sound pitch is a multiplication of @link(TCastleSound.Pitch), |
| 189 |
@link(TCastlePlayingSound.Pitch) and @link(TCastleSoundSource.Pitch) |
| 190 |
(if the sound is played through @link(TCastleSoundSource)). |
| 191 |
|
| 192 |
Changing this naturally also changes the audible sound. |
| 193 |
Each reduction by 50 percent equals a pitchshift of -12 semitones (one octave reduction). |
| 194 |
Each doubling equals a pitch shift of 12 semitones (one octave increase). |
| 195 |
|
| 196 |
Any value > 0 is allowed. } |
| 197 |
property Pitch: Single read FPitch write SetPitch {$ifdef FPC}default 1.0{$endif}; |
| 198 |
|
| 199 |
{ How important is the sound, between 0.0 (least important) to 1.0 (most important). |
| 200 |
|
| 201 |
The sound engine sometimes has to interrupt (or even not start at all) |
| 202 |
playback of some non-important sound, to have a good performance of audio mixing. |
| 203 |
In these cases, the sound with higher priority always "wins" over sound with lower |
| 204 |
priority. That is, sound with lower priority will be interrupted (the slot will be "stolen") |
| 205 |
to make room for sound with higher priority. |
| 206 |
|
| 207 |
Note: Many sound APIs (Unity, FMOD, Wwise, X3D...) have a similar property, |
| 208 |
with inconsistent range (minimum, maximum) and inconsistent meaning (some say "lower is more important", |
| 209 |
some say "higher is more important"). Our treatment of this property is similar to X3D, |
| 210 |
as it satisfies a number of important points: it defines easy to remember min/max (0 and 1), |
| 211 |
it is agnostic to the underlying precision (e.g. it has to map to 257 levels in FMOD, |
| 212 |
100 levels in Wwise). Also, "higher is more important" seems just more natural. } |
| 213 |
property Priority: Single read FPriority write SetPriority {$ifdef FPC}default 0.5{$endif}; |
| 214 |
|
| 215 |
{ Spatial sound is fully audible (with @link(Volume)) at this distance. |
| 216 |
See TSoundDistanceModel for a description how distance affects the sound volume. } |
| 217 |
property ReferenceDistance: Single read FReferenceDistance write SetReferenceDistance |
| 218 |
{$ifdef FPC}default DefaultReferenceDistance{$endif}; |
| 219 |
|
| 220 |
{ Distance at which sound volume stops attenuating. |
| 221 |
For the linear distance model (@link(TSoundEngine.DistanceModel SoundEngine.DistanceModel) = dmLinear) |
| 222 |
this is also a distance at which sound volume drops to zero (completely silent). |
| 223 |
See TSoundDistanceModel for a description how distance affects the sound volume. } |
| 224 |
property MaxDistance: Single read FMaxDistance write SetMaxDistance |
| 225 |
{$ifdef FPC}default DefaultMaxDistance{$endif}; |
| 226 |
end; |
| 227 |
|
| 228 |
{$endif read_interface} |
| 229 |
|
| 230 |
{$ifdef read_implementation} |
| 231 |
|
| 232 |
{ TCastleSoundChangeEventList ------------------------------------------------ } |
| 233 |
|
| 234 |
procedure TCastleSoundChangeEventList.ExecuteAll(const Sender: TCastleSound; const Change: TSoundChange); |
| 235 |
var |
| 236 |
I: Integer; |
| 237 |
begin |
| 238 |
{ We do this weird inverted "for" with extra condition, to work even when a notification |
| 239 |
may remove its own listener from the list. This can actually happen: |
| 240 |
in case of scBeforeBufferDestroyed, it notifies TCastlePlayingSound, |
| 241 |
and it will stop the sound, removing itself from notifications list. |
| 242 |
|
| 243 |
Testcase: examples/audio/game_3d_sound/ and exit while many "kaboom" sounds are playing. } |
| 244 |
|
| 245 |
for I := Count - 1 downto 0 do |
| 246 |
if I < Count then |
| 247 |
Items[I](Sender, Change); |
| 248 |
end; |
| 249 |
|
| 250 |
{ TCastleSound --------------------------------------------------------------- } |
| 251 |
|
| 252 |
constructor TCastleSound.Create(AOwner: TComponent); |
| 253 |
begin |
| 254 |
inherited; |
| 255 |
FStream := false; |
| 256 |
FVolume := 1.0; |
| 257 |
FPitch := 1.0; |
| 258 |
FMinGain := 0.0; |
| 259 |
FMaxGain := 1.0; |
| 260 |
FPriority := 0.5; |
| 261 |
FReferenceDistance := DefaultReferenceDistance; |
| 262 |
FMaxDistance := DefaultMaxDistance; |
| 263 |
FChangeNotifications := TCastleSoundChangeEventList.Create; |
| 264 |
end; |
| 265 |
|
| 266 |
destructor TCastleSound.Destroy; |
| 267 |
begin |
| 268 |
{ Just like in ReloadBuffer, we need to call scBeforeBufferDestroyed notification. |
| 269 |
This allows related TCastlePlayingSound to stop playback automatically |
| 270 |
when TCastleSound is destroyed. } |
| 271 |
DoChange(scBeforeBufferDestroyed); |
| 272 |
|
| 273 |
{ Use InternalSoundEngine instead of SoundEngine to avoid creating |
| 274 |
2nd SoundEngine instance, if this would be called at finalization |
| 275 |
(after 1st singleton SoundEngine destroyed). } |
| 276 |
if InternalSoundEngine <> nil then |
| 277 |
begin |
| 278 |
{$warnings off} // using deprecated that should be internal |
| 279 |
InternalSoundEngine.FreeBuffer(FBuffer); // this sets FBuffer = nil |
| 280 |
{$warnings on} |
| 281 |
end; |
| 282 |
|
| 283 |
FreeAndNil(FChangeNotifications); |
| 284 |
inherited; |
| 285 |
end; |
| 286 |
|
| 287 |
function TCastleSound.PropertySections(const PropertyName: String): TPropertySections; |
| 288 |
begin |
| 289 |
if (PropertyName = 'Url') or |
| 290 |
(PropertyName = 'Stream') or |
| 291 |
(PropertyName = 'Volume') or |
| 292 |
(PropertyName = 'Pitch') or |
| 293 |
(PropertyName = 'Priority') or |
| 294 |
(PropertyName = 'ReferenceDistance') or |
| 295 |
(PropertyName = 'MaxDistance') then |
| 296 |
Result := [psBasic] |
| 297 |
else |
| 298 |
Result := inherited PropertySections(PropertyName); |
| 299 |
end; |
| 300 |
|
| 301 |
procedure TCastleSound.ReloadBuffer; |
| 302 |
var |
| 303 |
SoundLoading: TSoundLoading; |
| 304 |
begin |
| 305 |
if FBuffer <> nil then // check nil to avoid accessing SoundEngine if not needed |
| 306 |
begin |
| 307 |
{ We first make scBeforeBufferDestroyed notification, so that sound sources playing |
| 308 |
this TCastleSound can be stopped. |
| 309 |
OpenAL makes warning if trying to free buffer used by playing sources. } |
| 310 |
DoChange(scBeforeBufferDestroyed); |
| 311 |
{$warnings off} // using deprecated that should be internal |
| 312 |
SoundEngine.FreeBuffer(FBuffer); // this sets FBuffer = nil |
| 313 |
{$warnings on} |
| 314 |
end; |
| 315 |
|
| 316 |
if Url <> '' then |
| 317 |
begin |
| 318 |
if Stream then |
| 319 |
SoundLoading := slStreaming |
| 320 |
else |
| 321 |
SoundLoading := slComplete; |
| 322 |
{ Using ExceptionOnError = false. Because |
| 323 |
- The programs can generally tolerate missing sound files, and continue just fine. |
| 324 |
- Error at OggVorbis reading may be caused by |
| 325 |
EOggVorbisMissingLibraryError, and we try to gracefully react to missing |
| 326 |
libraries, as it is easy to miss installation of some libs on some systems |
| 327 |
(like Linux) or package with appropriate DLLs (like Windows). } |
| 328 |
FBuffer := SoundEngine.LoadBuffer(Url, SoundLoading, false); |
| 329 |
DoChange(scAfterBufferCreated); |
| 330 |
end; |
| 331 |
end; |
| 332 |
|
| 333 |
procedure TCastleSound.Loaded; |
| 334 |
begin |
| 335 |
inherited; |
| 336 |
ReloadBuffer; |
| 337 |
end; |
| 338 |
|
| 339 |
procedure TCastleSound.SetStream(const Value: Boolean); |
| 340 |
begin |
| 341 |
if FStream <> Value then |
| 342 |
begin |
| 343 |
FStream := Value; |
| 344 |
if not IsLoading then |
| 345 |
ReloadBuffer; |
| 346 |
end; |
| 347 |
end; |
| 348 |
|
| 349 |
procedure TCastleSound.SetUrl(const Value: String); |
| 350 |
begin |
| 351 |
if FUrl <> Value then |
| 352 |
begin |
| 353 |
FUrl := Value; |
| 354 |
if not IsLoading then |
| 355 |
ReloadBuffer; |
| 356 |
end; |
| 357 |
end; |
| 358 |
|
| 359 |
procedure TCastleSound.LoadFromStream(const AStream: TStream; const MimeType: String); |
| 360 |
begin |
| 361 |
// TODO: unoptimal implementation, we should pass TStream downward, not base64-encode it |
| 362 |
Url := StreamToDataUri(AStream, MimeType); |
| 363 |
end; |
| 364 |
|
| 365 |
procedure TCastleSound.SetVolume(const Value: Single); |
| 366 |
begin |
| 367 |
if FVolume <> Value then |
| 368 |
begin |
| 369 |
FVolume := Value; |
| 370 |
DoChange(scAfterOther); |
| 371 |
end; |
| 372 |
end; |
| 373 |
|
| 374 |
procedure TCastleSound.SetPitch(const Value: Single); |
| 375 |
begin |
| 376 |
if FPitch <> Value then |
| 377 |
begin |
| 378 |
FPitch := Value; |
| 379 |
DoChange(scAfterOther); |
| 380 |
end; |
| 381 |
end; |
| 382 |
|
| 383 |
procedure TCastleSound.SetMinGain(const Value: Single); |
| 384 |
begin |
| 385 |
if FMinGain <> Value then |
| 386 |
begin |
| 387 |
FMinGain := Value; |
| 388 |
DoChange(scAfterOther); |
| 389 |
end; |
| 390 |
end; |
| 391 |
|
| 392 |
procedure TCastleSound.SetMaxGain(const Value: Single); |
| 393 |
begin |
| 394 |
if FMaxGain <> Value then |
| 395 |
begin |
| 396 |
FMaxGain := Value; |
| 397 |
DoChange(scAfterOther); |
| 398 |
end; |
| 399 |
end; |
| 400 |
|
| 401 |
procedure TCastleSound.SetPriority(const Value: Single); |
| 402 |
begin |
| 403 |
if FPriority <> Value then |
| 404 |
begin |
| 405 |
FPriority := Value; |
| 406 |
DoChange(scAfterOther); |
| 407 |
end; |
| 408 |
end; |
| 409 |
|
| 410 |
procedure TCastleSound.SetReferenceDistance(const Value: Single); |
| 411 |
begin |
| 412 |
if FReferenceDistance <> Value then |
| 413 |
begin |
| 414 |
FReferenceDistance := Value; |
| 415 |
DoChange(scAfterOther); |
| 416 |
end; |
| 417 |
end; |
| 418 |
|
| 419 |
procedure TCastleSound.SetMaxDistance(const Value: Single); |
| 420 |
begin |
| 421 |
if FMaxDistance <> Value then |
| 422 |
begin |
| 423 |
FMaxDistance := Value; |
| 424 |
DoChange(scAfterOther); |
| 425 |
end; |
| 426 |
end; |
| 427 |
|
| 428 |
procedure TCastleSound.DoChange(const Change: TSoundChange); |
| 429 |
begin |
| 430 |
FChangeNotifications.ExecuteAll(Self, Change); |
| 431 |
end; |
| 432 |
|
| 433 |
procedure TCastleSound.InternalAddChangeNotification(const Notify: TCastleSoundChangeEvent); |
| 434 |
begin |
| 435 |
FChangeNotifications.Add(Notify); |
| 436 |
end; |
| 437 |
|
| 438 |
procedure TCastleSound.InternalRemoveChangeNotification(const Notify: TCastleSoundChangeEvent); |
| 439 |
begin |
| 440 |
if FChangeNotifications <> nil then // may be nil when destroying, and we make notification |
| 441 |
FChangeNotifications.Remove(Notify); |
| 442 |
end; |
| 443 |
|
| 444 |
function TCastleSound.Duration: Single; |
| 445 |
begin |
| 446 |
if FBuffer <> nil then |
| 447 |
Result := FBuffer.Duration |
| 448 |
else |
| 449 |
Result := -1; |
| 450 |
end; |
| 451 |
|
| 452 |
function TCastleSound.DataFormat: TSoundDataFormat; |
| 453 |
begin |
| 454 |
if FBuffer <> nil then |
| 455 |
Result := FBuffer.DataFormat |
| 456 |
else |
| 457 |
Result := Default(TSoundDataFormat); // whatever, just not memory garbage |
| 458 |
end; |
| 459 |
|
| 460 |
function TCastleSound.Frequency: Cardinal; |
| 461 |
begin |
| 462 |
if FBuffer <> nil then |
| 463 |
Result := FBuffer.Frequency |
| 464 |
else |
| 465 |
Result := 0; |
| 466 |
end; |
| 467 |
|
| 468 |
{$endif read_implementation} |