Parasol Framework
  • Gallery
  • API
  • Wiki
  • GitHub
    • Audio
    • Core
    • Display
    • Fluid
    • Font
    • Network
    • Vector
    • Audio
    • Sound
    • File
    • MetaClass
    • Module
    • StorageDevice
    • Task
    • Thread
    • Time
    • Compression
    • Config
    • Script
    • XML
    • Controller
    • BlurFX
    • ColourFX
    • CompositeFX
    • ConvolveFX
    • DisplacementFX
    • FilterEffect
    • FloodFX
    • ImageFX
    • LightingFX
    • MergeFX
    • MorphologyFX
    • OffsetFX
    • RemapFX
    • SourceFX
    • TurbulenceFX
    • WaveFunctionFX
    • Scintilla
    • ScintillaSearch
    • Bitmap
    • Clipboard
    • Display
    • Document
    • Font
    • Picture
    • Pointer
    • Surface
    • SVG
    • ClientSocket
    • HTTP
    • NetClient
    • NetSocket
    • Proxy
    • Vector
    • VectorClip
    • VectorColour
    • VectorEllipse
    • VectorFilter
    • VectorGradient
    • VectorGroup
    • VectorImage
    • VectorPath
    • VectorPattern
    • VectorPolygon
    • VectorRectangle
    • VectorScene
    • VectorShape
    • VectorSpiral
    • VectorText
    • VectorTransition
    • VectorViewport
    • VectorWave

Sound Class

High-level audio sample playback interface with intelligent resource management and format detection.

The Sound class provides a comprehensive, user-friendly interface for audio sample playback that abstracts the complexities of audio hardware management whilst delivering professional-quality results. Designed as the primary interface for general-purpose audio operations, the Sound class automatically handles resource allocation, format detection, hardware abstraction, and intelligent streaming decisions to provide optimal performance across diverse system configurations.

The Sound class implements robust file format support with automatic detection and validation:

  • Native WAVE Support: Complete support for WAVE format files including all standard PCM encodings, multiple bit depths (8/16-bit), and both mono and stereo configurations
  • Automatic Format Detection: File format identification occurs automatically during initialisation based on file headers and content analysis
  • Extensible Architecture: Additional audio formats (MP3, OGG, FLAC, AAC) can be supported through Sound class extensions and codec plugins
  • Validation and Error Handling: Comprehensive file validation prevents playback of corrupted or unsupported audio data

The following demonstrates advanced Sound class usage including pitch control and event handling:

local snd = obj.new('sound', {
   path = 'audio:samples/piano_c4.wav',
   note = 'C6',    -- Play two octaves higher
   volume = 0.8,   -- Reduce volume to 80%
   onStop = function(Sound)
      print('Playback completed')
      proc.signal()
   end
})

snd.acActivate()
proc.sleep()  -- Wait for completion

Structure

The Sound class consists of the following fields:

Access
NameTypeComment
  ActiveINTReturns true if the sound sample is being played back.
  AudioOBJECTIDRefers to the audio object/device to use for playback.

Set this field if a specific Audio object should be targeted when playing the sound sample.

  BitsPerSampleINTIndicates the sample rate of the audio sample, typically 8 or 16 bit.
  BytesPerSecondINTThe flow of bytes-per-second when the sample is played at normal frequency.

This field is set on initialisation. It indicates the total number of bytes per second that will be played if the sample is played back at its normal frequency.

  ChannelIndexINTRefers to the channel that the sound is playing through.

This field reflects the audio channel index that the sound is currently playing through, or has most recently played through.

  CompressionINTDetermines the amount of compression used when saving an audio sample.

Setting the Compression field will determine how much compression is applied when saving an audio sample. The range of compression is 0 to 100%, with 100% being the strongest level available while 0% is uncompressed and loss-less. This field is ignored if the file format does not support compression.

  DurationDOUBLEReturns the duration of the sample, measured in seconds.
  FlagsSDFOptional initialisation flags.
NameDescription
SDF::LOOPEnables sample looping. The LoopStart and LoopEnd fields determine where the looping area lies within the sample data.
SDF::NEWCreate the sample from scratch (e.g. for audio recording purposes).
SDF::RESTRICT_PLAYRestricts playback so that the sound can never play on more than one channel at any given time.
SDF::STEREOIndicates that the sound has multiple audio channels.
SDF::STREAMRead-Only. Indicates that streaming is enabled.
  FrequencyINTThe frequency of a sampled sound is specified here.

This field specifies the frequency of the sampled sound data. If the frequency cannot be determined from the source, this value will be zero.

Note that if the playback frequency needs to be altered, set the Playback field.

  HeaderINT8 []Contains the first 128 bytes of data in a sample's file header.

The Header field is a pointer to a 128 byte buffer that contains the first 128 bytes of information read from an audio file on initialisation. This special field is considered to be helpful only to developers writing add-on components for the sound class.

The buffer that is referred to by the Header field is not populated until the Init action is called on the sound object.

  LengthINTIndicates the total byte-length of sample data.

This field specifies the length of the sample data in bytes. To get the length of the sample in seconds, divide this value by the BytesPerSecond field.

  LoopEndINTThe byte position at which sample looping will end.

When using looped samples (via the SDF::LOOP flag), set the LoopEnd field if the sample should end at a position that is earlier than the sample's actual length. The LoopEnd value is specified in bytes and must be less or equal to the length of the sample and greater than the LoopStart value.

  LoopStartINTThe byte position at which sample looping begins.

When using looped samples (via the SDF::LOOP flag), set the LoopStart field if the sample should begin at a position other than zero. The LoopStart value is specified in bytes and must be less than the length of the sample and the LoopEnd value.

Note that the LoopStart variable does not affect the position at which playback occurs for the first time - it only affects the restart position when the end of the sample is reached.

  NoteSTRINGThe musical note to use when playing a sound sample.

Set the Note field to alter the playback frequency of a sound sample. Setting this field as opposed to the Playback frequency will assure that the sample is played at a correctly scaled tone.

The Note field can be set using either string or integer based format. If using the integer format, the chosen value will reflect the position on a musical keyboard. A value of zero refers to the middle C key. Each octave is measured in sets of 12 notes, so a value of 24 would indicate a C note at 3 times normal playback. To play at lower values, simply choose a negative integer to slow down sample playback.

Setting the Note field with the string format is useful if human readability is valuable. The correct format is KEY OCTAVE SHARP. Here are some examples: C5, D7#, G2, E3S.

The middle C key for this format is C5. The maximum octave that you can achieve for the string format is 9 and the lowest is 0. Use either the S character or the # character for referral to a sharp note.

NameDescription
NOTE::A
NOTE::AS
NOTE::B
NOTE::C
NOTE::CS
NOTE::D
NOTE::DS
NOTE::E
NOTE::F
NOTE::FS
NOTE::G
NOTE::GS
NOTE::OCTAVE
  OctaveINTThe octave to use for sample playback.

The Octave field determines the octave to use when playing back a sound sample. The default setting is zero, which represents the octave at which the sound was sampled. Setting a negative octave will lower the playback rate, while positive values raise the playback rate. The minimum octave setting is -5 and the highest setting is +5.

The octave can also be adjusted by setting the Note field. Setting the Octave field directly is useful if you need to quickly double or halve the playback rate.

  OnStopFUNCTIONThis callback is triggered when sample playback stops.

Set OnStop to a callback function to receive an event trigger when sample playback stops. The prototype for the function is void OnStop(*Sound).

The timing of this event does not guarantee precision, but should be accurate to approximately 1/100th of a second in most cases.

  PanDOUBLEDetermines the horizontal position of a sound when played through stereo speakers.

The Pan field adjusts the "horizontal position" of a sample that is being played through stereo speakers. The default value for this field is zero, which plays the sound through both speakers at an equal level. The minimum value is -1.0 to force play through the left speaker and the maximum value is 1.0 for the right speaker.

  PathSTRINGLocation of the audio sample data.

This field must refer to a file that contains the audio data that will be loaded. If creating a new sample with the SDF::NEW flag, it is not necessary to define a file source.

  PlaybackINTThe playback frequency of the sound sample can be defined here.

Set this field to define the exact frequency of a sample's playback. The playback frequency can be modified at any time, including during audio playback if real-time adjustments to a sample's audio output rate is desired.

  PositionINT64The current playback position.

The current playback position of the audio sample is indicated by this field. Writing to the field will alter the playback position, either when the sample is next played, or immediately if it is currently playing.

  PriorityINTThe priority of a sound in relation to other sound samples being played.

The playback priority of the sample is defined here. This helps to determine if the sample should be played when all available mixing channels are busy. Naturally, higher priorities are played over samples with low priorities.

The minimum priority value allowed is -100, the maximum is 100.

  StreamSTREAMDefines the preferred streaming method for the sample.

The Stream field controls how the Sound class manages memory and playback for audio samples. This setting directly influences memory consumption, playback latency, and system resource utilisation.

Available streaming modes:

NameDescription
STREAM::ALWAYSStream if the sample length exceeds 64k.
STREAM::NEVERNo streaming - load all data into memory.
STREAM::SMARTSmart streaming is the default. If the sample appears to be relatively small with respect to available system RAM, it will be loaded into memory. Otherwise it will be streamed.

Smart and Always streaming modes use significantly less memory for large samples, making them suitable for applications that handle extensive audio libraries. Never streaming provides the fastest playback initiation but may exhaust system memory with large or numerous samples.

Memory-resident samples (Never streaming) offer zero-latency playback initiation, whilst streamed samples may have a brief delay as the initial buffer is populated. However, once streaming begins, there should be no perceptible difference in audio quality or continuity.

The Smart streaming mode monitors system resources and sample characteristics to make optimal decisions. This mode adapts to changing conditions and provides the best balance for most applications without requiring manual configuration.

  VolumeDOUBLEThe volume to use when playing the sound sample.

The field specifies the volume of a sound in the range 0 - 1.0 (low to high). Setting this field during sample playback will dynamically alter the volume.

Actions

The following actions are currently supported:

ActivatePlays the audio sample.
DeactivateStops the audio sample and resets the playback position.
DisableDisable playback of an active audio sample, equivalent to pausing.
EnableContinues playing a sound if it has been disabled.
GetKeyRetrieve custom key values.
ERR acGetKey(*Object, CSTRING Key, STRING Value, INT Size)
ParameterDescription
KeyThe name of a key value.
ValuePointer to a buffer space large enough to hold the retrieved value.
SizeIndicates the byte size of the Buffer.

The following custom key values are formally recognised and may be defined automatically when loading sample files:

NameDescription
AuthorThe name of the person or organisation that created the sound sample.
CopyrightCopyright details of an audio sample.
DescriptionLong description for an audio sample.
DisclaimerThe disclaimer associated with an audio sample.
SoftwareThe name of the application that was used to record the audio sample.
TitleThe title of the audio sample.
QualityThe compression quality value if the source is an MP3 stream.
ReadRead decoded audio from the sound sample.
ERR acRead(*Object, APTR Buffer, INT Length, INT *Result)
ParameterDescription
BufferPoints a buffer that will receive the data.
LengthThe total number of bytes to read from the object. This value cannot exceed the size of the Buffer.
ResultThe Read action will write this parameter with the total number of bytes read into the Buffer.

This action will read decoded audio from the sound sample. Decoding is a live process and it may take some time for all data to be returned if the requested amount of data is considerable. The starting point for the decoded data is determined by the Position value.

SaveToObjectSaves audio sample data to an object.
ERR acSaveToObject(*Object, OBJECTID Dest, CLASSID ClassID)
ParameterDescription
DestRefers to an object that will receive the encoded data.
ClassIDCan refer to a sub-class that should be used when encoding the data.
SeekMoves the cursor position for reading data.
ERR acSeek(*Object, DOUBLE Offset, INT Position)
ParameterDescription
OffsetThe desired offset to seek to, relative to the Position parameter.
PositionThe position that defines the starting point for Offset.

Use Seek to move the read cursor within the decoded audio stream and update Position. This will affect the Read action. If the sample is in active playback at the time of the call, the playback position will also be moved.

SetKeyDefine custom tags that will be saved with the sample data.
ERR acSetKey(*Object, CSTRING Key, CSTRING Value)
ParameterDescription
KeyThe name of the target key.
ValueThe string value to associate with Key.
Sound class documentation © Paul Manias © 2002-2025

NOTE Type

Definitions for the Note field. An 'S' indicates a sharp note.

NameDescription
NOTE::A
NOTE::AS
NOTE::B
NOTE::C
NOTE::CS
NOTE::D
NOTE::DS
NOTE::E
NOTE::F
NOTE::FS
NOTE::G
NOTE::GS
NOTE::OCTAVE
Sound module documentation © Paul Manias © 2002-2025

SDF Type

Sound flags

NameDescription
SDF::LOOPEnables sample looping. The LoopStart and LoopEnd fields determine where the looping area lies within the sample data.
SDF::NEWCreate the sample from scratch (e.g. for audio recording purposes).
SDF::RESTRICT_PLAYRestricts playback so that the sound can never play on more than one channel at any given time.
SDF::STEREOIndicates that the sound has multiple audio channels.
SDF::STREAMRead-Only. Indicates that streaming is enabled.
Sound module documentation © Paul Manias © 2002-2025

STREAM Type

Streaming options

NameDescription
STREAM::ALWAYSStream if the sample length exceeds 64k.
STREAM::NEVERNo streaming - load all data into memory.
STREAM::SMARTSmart streaming is the default. If the sample appears to be relatively small with respect to available system RAM, it will be loaded into memory. Otherwise it will be streamed.
Sound module documentation © Paul Manias © 2002-2025