logo SERENITY
Game Systems Foundation
Search Results for

    Show / Hide Table of Contents

    Class UnityAudioPlayerService

    Unity-specific audio player service that manages audio playback through AudioSource components. Supports both UI and music audio player types with game settings integration.

    Inheritance
    object
    UnityAudioPlayerService
    Implements
    IAudioPlayerService
    IService
    IFoundationSettings
    Namespace: Serenity.AudioPlayer.Infrastructure.Services
    Assembly: Serenity.UnityAudioPlayer.Infrastructure.dll
    Syntax
    public class UnityAudioPlayerService : MonoBehaviour, IAudioPlayerService, IService, IFoundationSettings

    Constructors

    UnityAudioPlayerService()

    Declaration
    public UnityAudioPlayerService()

    Fields

    Guid

    Declaration
    public string Guid
    Field Value
    Type Description
    string

    GUID for this service used by editor tools and serialization.

    Id

    Declaration
    public string Id
    Field Value
    Type Description
    string

    Unique identifier for this audio player service instance.

    _audioGameSettings

    Declaration
    protected UnityAudioGameSettingsDefinition _audioGameSettings
    Field Value
    Type Description
    UnityAudioGameSettingsDefinition

    Audio game settings definition used for resolving audio clips from game settings.

    _audioPlayerType

    Declaration
    protected AudioPlayerType _audioPlayerType
    Field Value
    Type Description
    AudioPlayerType

    Type of audio player (UI or Music) determining behavior and event subscriptions.

    _audioPlayerUseCases

    Declaration
    protected AudioPlayerUseCases _audioPlayerUseCases
    Field Value
    Type Description
    AudioPlayerUseCases

    Use cases for audio player operations and business logic.

    _audioSources

    Declaration
    protected AudioSource[] _audioSources
    Field Value
    Type Description
    AudioSource[]

    Array of Unity AudioSource components used for audio playback.

    _candidateSelector

    Declaration
    protected IAudioPriorityCandidateSelector _candidateSelector
    Field Value
    Type Description
    IAudioPriorityCandidateSelector

    Selects which busy source (if any) should be reassigned to a higher-priority sound. Pure domain logic, kept separate so it can be unit tested without Unity.

    _eventDispatcherService

    Declaration
    protected IEventDispatcherService _eventDispatcherService
    Field Value
    Type Description
    IEventDispatcherService

    Event dispatcher service for subscribing to and handling audio-related events.

    _gameSettingsService

    Declaration
    protected IGameSettingsService _gameSettingsService
    Field Value
    Type Description
    IGameSettingsService

    Game settings service for accessing game configuration.

    _isEnabled

    Declaration
    protected bool _isEnabled
    Field Value
    Type Description
    bool

    Flag indicating whether the audio player service is enabled.

    _logService

    Declaration
    protected ILogService _logService
    Field Value
    Type Description
    ILogService

    Logging service for error reporting and debugging.

    _sequenceCounter

    Declaration
    protected long _sequenceCounter
    Field Value
    Type Description
    long

    Monotonically increasing counter assigned to each started sound to break priority ties (oldest sound wins). Reset whenever the source pool is (re)assigned.

    _sourceStates

    Declaration
    protected UnityAudioPlayerSourceState[] _sourceStates
    Field Value
    Type Description
    UnityAudioPlayerSourceState[]

    Per-source runtime metadata kept parallel to _audioSources, used to make priority-based replacement decisions when the pool is full.

    Properties

    AudioGameSettings

    Declaration
    public IGameSettingsDefinition AudioGameSettings { get; set; }
    Property Value
    Type Description
    IGameSettingsDefinition

    IsEnabled

    Declaration
    public bool IsEnabled { get; set; }
    Property Value
    Type Description
    bool

    Indicates if the audio player service is enabled and can play audio.

    LogService

    Declaration
    public ILogService LogService { get; set; }
    Property Value
    Type Description
    ILogService

    Methods

    AllocateSourceStates()

    Allocates a fresh UnityAudioPlayerSourceState per managed source and resets the tie-break sequence counter.

    Declaration
    protected void AllocateSourceStates()

    ApplyClipStartOffset(AudioSource, AudioClip, float)

    Positions the source's playhead at the requested start offset before playback, clamped to the valid range of the clip so an out-of-range offset never throws.

    Declaration
    protected void ApplyClipStartOffset(AudioSource aS, AudioClip ac, float offsetSeconds)
    Parameters
    Type Name Description
    AudioSource aS

    The source about to play.

    AudioClip ac

    The resolved Unity audio clip.

    float offsetSeconds

    Requested offset from the start of the clip, in seconds.

    ApplyClipToSource(AudioSource, AudioPlayerClip, AudioClip)

    Applies all clip settings to the source, including the Serenity→Unity priority mapping.

    Declaration
    protected void ApplyClipToSource(AudioSource aS, AudioPlayerClip clip, AudioClip ac)
    Parameters
    Type Name Description
    AudioSource aS

    Target source.

    AudioPlayerClip clip

    Clip whose settings to apply.

    AudioClip ac

    Resolved Unity audio clip.

    ApplyPlaybackPlacement(AudioSource, AudioPlayerPlayClipInput)

    Derives the source's spatial mode and emitter position from whether a world position was supplied:
    • With a PlaybackPosition → the sound is 3D (spatialBlend = 1) and the emitter is moved to that world position.
    • Without a position → the sound is 2D (spatialBlend = 0) and the emitter is left where it is.

    Declaration
    protected void ApplyPlaybackPlacement(AudioSource aS, AudioPlayerPlayClipInput input)
    Parameters
    Type Name Description
    AudioSource aS

    The source about to play.

    AudioPlayerPlayClipInput input

    Input carrying the optional playback position.

    BuildActiveCandidates()

    Builds the list of currently playing, tracked slots as Unity-agnostic candidates for the priority selector. Sources that are playing but have no tracked state are intentionally excluded so they are never reassigned.

    Declaration
    protected List<AudioPlaybackCandidate> BuildActiveCandidates()
    Returns
    Type Description
    List<AudioPlaybackCandidate>

    Snapshots of the replaceable-by-policy active slots.

    Enable()

    Declaration
    public void Enable()

    GetAudioPlayerType()

    Retrieves the audio player type (UI or Music) of this service.

    Declaration
    public AudioPlayerType GetAudioPlayerType()
    Returns
    Type Description
    AudioPlayerType

    Current audio player type

    GetAudioSources()

    Retrieves the array of AudioSource components managed by this audio player service.

    Declaration
    public AudioSource[] GetAudioSources()
    Returns
    Type Description
    AudioSource[]

    Array of AudioSource components managed by this audio player service

    GetAudioSourcesPlayingCount()

    Counts the number of audio sources currently playing clips.
    Useful for monitoring audio service load and debugging playback issues.

    Declaration
    public int GetAudioSourcesPlayingCount()
    Returns
    Type Description
    int

    Number of active audio sources with playing clips

    GetAvailableAudioSource()

    Finds the first available (non-playing) audio source from the pool.
    Used for audio clip playback to avoid overlapping sounds on the same source.

    Declaration
    protected AudioSource GetAvailableAudioSource()
    Returns
    Type Description
    AudioSource

    First available AudioSource component, null if all sources are busy

    GetAvailableAudioSourceIndex()

    Finds the index of the first available (non-playing) audio source in the pool.

    Declaration
    protected int GetAvailableAudioSourceIndex()
    Returns
    Type Description
    int

    Index of the first free source, or -1 if all sources are busy.

    GetId()

    Retrieves the event dispatcher service used by this audio player.

    Declaration
    public string GetId()
    Returns
    Type Description
    string

    Current event dispatcher service instance

    Initialize(IGameSettingsService, IAudioPlayerSettings, object, IEventDispatcherService, ILogService)

    Initializes the audio player service with dependencies and configuration.

    Declaration
    public void Initialize(IGameSettingsService gameSettingsService, IAudioPlayerSettings settings, object audioSourceList, IEventDispatcherService eventDispatcherService, ILogService logService)
    Parameters
    Type Name Description
    IGameSettingsService gameSettingsService

    Game settings service for configuration lookup

    IAudioPlayerSettings settings

    Audio player settings containing configuration

    object audioSourceList

    GameObject containing AudioSource components

    IEventDispatcherService eventDispatcherService

    Event dispatcher for audio playback events

    ILogService logService

    Logging service for error reporting

    InitializeEventDispatcher(IEventDispatcherService)

    Initializes event dispatcher integration and subscribes to relevant audio events.

    Declaration
    public void InitializeEventDispatcher(IEventDispatcherService eventDispatcherService)
    Parameters
    Type Name Description
    IEventDispatcherService eventDispatcherService

    Event dispatcher service to integrate with

    PauseAllClips()

    Pauses all currently playing audio clips on all managed audio sources.
    Clips can be resumed later without losing their playback position.

    Declaration
    public void PauseAllClips()

    PlayClip(AudioPlayerPlayClipInput)

    Plays an audio clip.
    Uses the first free audio source when one exists; otherwise consults the clip's AudioPriorityPolicy to decide whether to reassign a lower-priority source.

    Declaration
    public AudioPlayerPlayClipOutput PlayClip(AudioPlayerPlayClipInput input)
    Parameters
    Type Name Description
    AudioPlayerPlayClipInput input

    Input DTO containing service ID and audio clip to play

    Returns
    Type Description
    AudioPlayerPlayClipOutput

    Output DTO with playback result details, or null when the clip was not played (service disabled, or no free/replaceable source for the clip's policy)

    PlayClipAndGetAudioSource(AudioPlayerPlayClipInput)

    Plays an audio clip and returns the Unity AudioSource used for playback.
    Intended for Unity-layer subclasses that need direct AudioSource access for playback lifecycle management (e.g., track ending detection).
    This method keeps AudioSource entirely within the Unity layer.

    Declaration
    protected AudioSource PlayClipAndGetAudioSource(AudioPlayerPlayClipInput input)
    Parameters
    Type Name Description
    AudioPlayerPlayClipInput input

    Input DTO containing service ID and audio clip to play.

    Returns
    Type Description
    AudioSource

    The AudioSource used for playback, or null if playback could not start.

    PlayClipScheduledAndGetAudioSource(AudioPlayerPlayClipInput, double)

    Plays an audio clip on a future DSP timeline position using UnityEngine.AudioSource.PlayScheduled(System.Double), returning the AudioSource used.
    Intended for sample-accurate sequencing such as the music player's tail-preserving loop, where the next loop voice must start exactly at the loop seam. Native UnityEngine.AudioSource.loop is forced off because looping is driven manually by the scheduler.

    Declaration
    protected AudioSource PlayClipScheduledAndGetAudioSource(AudioPlayerPlayClipInput input, double dspStartTime)
    Parameters
    Type Name Description
    AudioPlayerPlayClipInput input

    Input DTO containing the clip and its ClipStartOffsetSeconds.

    double dspStartTime

    Absolute UnityEngine.AudioSettings.dspTime at which playback should begin.

    Returns
    Type Description
    AudioSource

    The AudioSource used for playback, or null if playback could not start.

    RecordSourceState(int, AudioPlayerClip)

    Records the runtime state for the slot that just started a clip.

    Declaration
    protected void RecordSourceState(int index, AudioPlayerClip clip)
    Parameters
    Type Name Description
    int index

    Slot index that started playing.

    AudioPlayerClip clip

    Clip that was started.

    ResolveTargetSourceIndex(AudioPlayerClip, string)

    Resolves the index of the source to play on.
    Returns a free source when available; otherwise applies the clip's AudioPriorityPolicy to pick a replaceable lower-priority source, logging the outcome. Returns -1 when the clip should not be played.

    Declaration
    protected int ResolveTargetSourceIndex(AudioPlayerClip clip, string logMethod)
    Parameters
    Type Name Description
    AudioPlayerClip clip

    The clip being requested.

    string logMethod

    Calling method name, used as a logging tag.

    Returns
    Type Description
    int

    Index into _audioSources, or -1 when no source should be used.

    ResumeAllClips()

    Resumes all previously paused audio clips on all managed audio sources.
    Only affects sources that were paused, not stopped.

    Declaration
    public void ResumeAllClips()

    SerenityPriorityToUnityPriority(int)

    Maps a Serenity priority (higher = more important) to Unity's inverted AudioSource.priority scale (0 = highest, 255 = lowest). This keeps Unity's own voice virtualization aligned with Serenity semantics without leaking Unity's model into the domain.

    Declaration
    public static int SerenityPriorityToUnityPriority(int serenityPriority)
    Parameters
    Type Name Description
    int serenityPriority

    Serenity priority (higher = more important).

    Returns
    Type Description
    int

    Unity priority in the range [0, 255].

    SetAudioPlayerType(AudioPlayerType)

    Retrieves the event dispatcher service used by this audio player.

    Declaration
    public void SetAudioPlayerType(AudioPlayerType audioType)
    Parameters
    Type Name Description
    AudioPlayerType audioType

    SetAudioSources(AudioSource[])

    Sets the array of AudioSource components managed by this audio player service.
    Also (re)allocates the parallel per-source state used for priority replacement.

    Declaration
    public void SetAudioSources(AudioSource[] audioSources)
    Parameters
    Type Name Description
    AudioSource[] audioSources

    Array of AudioSource components to manage

    SetEventDispatcherService(IEventDispatcherService)

    Sets the event dispatcher service for this audio player.

    Declaration
    public void SetEventDispatcherService(IEventDispatcherService eventDispatcherService)
    Parameters
    Type Name Description
    IEventDispatcherService eventDispatcherService

    Event dispatcher service to set

    StopAllClips()

    Stops all currently playing audio clips on all managed audio sources.
    Clips will restart from the beginning if played again.

    Declaration
    public void StopAllClips()

    SubscribeToEventDispatcherEvents()

    Subscribes to event dispatcher events based on audio player type.
    UI audio players listen for both direct clip events and game settings events.

    Declaration
    public virtual void SubscribeToEventDispatcherEvents()

    TryPlayClipOnSource(AudioPlayerPlayClipInput, string, double?)

    Shared playback core for PlayClip(AudioPlayerPlayClipInput) and PlayClipAndGetAudioSource(AudioPlayerPlayClipInput).
    Resolves a target source (free, or a reassigned lower-priority one per the clip's policy), loads and applies the clip, relocates the emitter, starts playback, and records the slot's runtime state.

    Declaration
    protected AudioSource TryPlayClipOnSource(AudioPlayerPlayClipInput input, string logMethod, double? scheduledDspTime = null)
    Parameters
    Type Name Description
    AudioPlayerPlayClipInput input

    Input DTO containing the clip plus optional playback position and spatial blend override.

    string logMethod

    Calling method name, used as a logging tag.

    double? scheduledDspTime

    When supplied, playback is scheduled to start at this absolute UnityEngine.AudioSettings.dspTime via UnityEngine.AudioSource.PlayScheduled(System.Double) with native looping forced off; when null, playback starts immediately via UnityEngine.AudioSource.Play.

    Returns
    Type Description
    AudioSource

    The AudioSource used, or null when the clip was not played.

    ValidateAudioGameSettings(string, UnityAudioGameSettingsDefinition)

    Validates that audio game settings are properly configured with valid clip definition GUIDs.

    Declaration
    public virtual void ValidateAudioGameSettings(string id, UnityAudioGameSettingsDefinition audioGameSettings)
    Parameters
    Type Name Description
    string id

    Service identifier for error reporting

    UnityAudioGameSettingsDefinition audioGameSettings

    Audio game settings to validate

    Exceptions
    Type Condition
    Exception

    Thrown when settings are invalid or clip definitions not found

    Implements

    IAudioPlayerService
    IService
    IFoundationSettings
    In this article
    © 2026 Serenity. All Rights Reserved