Class UnityMusicPlayerService
Unity implementation of music player service providing music playback functionality.
Extends UnityAudioPlayerService with specialized music track management, playlist controls, and game settings integration.
Handles track sequencing, repeat modes, and event-driven music playback through the application's event dispatcher system.
Supports both direct music track playing and game settings-based music selection for dynamic audio configuration.
Namespace: Serenity.MusicPlayer.Infrastructure.Services
Assembly: Serenity.UnityMusicPlayer.Infrastructure.dll
Syntax
public class UnityMusicPlayerService : UnityAudioPlayerService, IMusicPlayerService, IService, IFoundationSettings, IUnityMusicPlayerRuntime
Constructors
UnityMusicPlayerService()
Declaration
public UnityMusicPlayerService()
Fields
TRANSITION_LOG_CATEGORY
Log category for music transition diagnostics.
Declaration
protected const string TRANSITION_LOG_CATEGORY = "MusicPlayer"
Field Value
| Type | Description |
|---|---|
| string |
_activeTransition
Active fade/cross-fade coroutine, or null when no transition is running.
Declaration
protected Coroutine _activeTransition
Field Value
| Type | Description |
|---|---|
| Coroutine |
_currentMusicTrackIndex
Index of the currently selected/playing track in the playlist.
Declaration
protected int _currentMusicTrackIndex
Field Value
| Type | Description |
|---|---|
| int |
_currentTrackAudioSource
Unity AudioSource component for the currently playing track.
Declaration
protected AudioSource _currentTrackAudioSource
Field Value
| Type | Description |
|---|---|
| AudioSource |
_currentTrackId
Id of the song currently owning playback, used to detect a re-request of the already-playing song when _ignoreRequestIfAlreadyPlaying is enabled. Null when nothing is playing.
Declaration
protected string _currentTrackId
Field Value
| Type | Description |
|---|---|
| string |
_isPlaying
Flag indicating whether music is currently playing.
Declaration
protected bool _isPlaying
Field Value
| Type | Description |
|---|---|
| bool |
_isRepeatingTrack
Flag indicating whether the current track should repeat when it ends.
Declaration
protected bool _isRepeatingTrack
Field Value
| Type | Description |
|---|---|
| bool |
_loopActive
True while a tail-preserving loop is scheduling its seams each frame.
Declaration
protected bool _loopActive
Field Value
| Type | Description |
|---|---|
| bool |
_loopGeneration
Monotonic token identifying the active loop session; bumped whenever the loop is reset so any in-flight tail fade-out coroutines from a previous session stop touching their (possibly reused) source.
Declaration
protected int _loopGeneration
Field Value
| Type | Description |
|---|---|
| int |
_loopPauseRemainingDsp
Remaining DSP time to the next loop seam captured at pause, restored on resume.
Declaration
protected double _loopPauseRemainingDsp
Field Value
| Type | Description |
|---|---|
| double |
_loopSegmentDsp
Length in seconds of every loop iteration after the first (EndTime - StartTime).
Declaration
protected double _loopSegmentDsp
Field Value
| Type | Description |
|---|---|
| double |
_loopSuspendedByPause
True when a tail-preserving loop was suspended by PauseSong() and should resume.
Declaration
protected bool _loopSuspendedByPause
Field Value
| Type | Description |
|---|---|
| bool |
_loopTrack
Track currently driving a tail-preserving loop, or null when no such loop is active.
Declaration
protected MusicTrack _loopTrack
Field Value
| Type | Description |
|---|---|
| MusicTrack |
_musicTracks
Collection of available music tracks in the playlist.
Declaration
protected List<MusicTrack> _musicTracks
Field Value
| Type | Description |
|---|---|
| List<MusicTrack> |
_nextLoopDspTime
Absolute UnityEngine.AudioSettings.dspTime at which the next loop voice must be scheduled.
Declaration
protected double _nextLoopDspTime
Field Value
| Type | Description |
|---|---|
| double |
_previousTrackAudioSource
Source playing the outgoing track during a fade/cross-fade transition. Null when no transition is running.
Declaration
protected AudioSource _previousTrackAudioSource
Field Value
| Type | Description |
|---|---|
| AudioSource |
_singleTrackMode
Flag indicating that the service is playing a single explicit track (PlaySongById) rather than the playlist.
Declaration
protected bool _singleTrackMode
Field Value
| Type | Description |
|---|---|
| bool |
Methods
AddMusicTrack(MusicTrack)
Adds a single music track to the current playlist.
Appends the provided music track to the existing collection of tracks.
Allows for dynamic expansion of the music library during runtime.
Declaration
public virtual void AddMusicTrack(MusicTrack musicTrack)
Parameters
| Type | Name | Description |
|---|---|---|
| MusicTrack | musicTrack | The MusicTrack to add to the playlist. |
GetCurrentMusicTrack()
Gets the currently selected music track from the playlist.
Returns the track at the current index position in the music tracks collection.
Used for displaying current track information and managing playback state.
Declaration
public virtual MusicTrack GetCurrentMusicTrack()
Returns
| Type | Description |
|---|---|
| MusicTrack | The MusicTrack currently selected for playback. |
GetCurrentTrackAudioSource()
Gets the Unity AudioSource component for the currently playing track.
Provides access to the AudioSource for advanced audio control and monitoring.
Returns null if no track is currently playing.
Declaration
public virtual AudioSource GetCurrentTrackAudioSource()
Returns
| Type | Description |
|---|---|
| AudioSource | The AudioSource component of the current track, or null if none is playing. |
GetMusicTrackById(string)
Retrieves a music track from the playlist by its unique identifier.
Searches through the loaded music tracks collection to find a matching track ID.
Returns null if no matching track is found.
Declaration
public virtual MusicTrack GetMusicTrackById(string id)
Parameters
| Type | Name | Description |
|---|---|---|
| string | id | The unique identifier of the music track to retrieve. |
Returns
| Type | Description |
|---|---|
| MusicTrack | The MusicTrack with the specified ID, or null if not found. |
GetMusicTracks()
Gets the complete collection of available music tracks.
Returns the current playlist containing all loaded music tracks.
Used for playlist management and track selection operations.
Declaration
public virtual List<MusicTrack> GetMusicTracks()
Returns
| Type | Description |
|---|---|
| List<MusicTrack> | The complete list of available MusicTrack objects. |
PauseSong()
Pauses the currently playing music track.
Sets the playing state to false and pauses all active audio clips.
Music can be resumed later from the same position using ResumeSong.
Declaration
public virtual void PauseSong()
PlayNextSong()
Advances to and plays the next song in the playlist.
Increments the current track index, wrapping to the beginning if at the end of the playlist.
Stops the current song and immediately starts playing the next track.
Declaration
public virtual void PlayNextSong()
PlayPreviousSong()
Goes back to and plays the previous song in the playlist.
Decrements the current track index, wrapping to the end if at the beginning of the playlist.
Stops the current song and immediately starts playing the previous track.
Declaration
public virtual void PlayPreviousSong()
PlaySong(MusicPlayerTransitionType, float)
Starts playback of the currently selected music track, transitioning out the previous track when one is active.
Falls back to CUT when the implementation cannot safely perform the requested transition.
Declaration
public virtual void PlaySong(MusicPlayerTransitionType transitionType = 0, float transitionDuration = 0.5)
Parameters
| Type | Name | Description |
|---|---|---|
| MusicPlayerTransitionType | transitionType | Transition strategy applied when moving from the current track to the new one. |
| float | transitionDuration | Duration of the transition in seconds. Ignored for CUT. |
PlaySongById(string, bool, MusicPlayerTransitionType, float)
Starts playback of a specific music track resolved by its id, independently of the playlist position.
Resolves the id against the configured music tracks list and plays it with the requested loop behavior,
transitioning out the previous track when one is active. Falls back to CUT
when the implementation cannot safely perform the requested transition.
Declaration
public virtual void PlaySongById(string musicTrackId, bool loop, MusicPlayerTransitionType transitionType = 0, float transitionDuration = 0.5)
Parameters
| Type | Name | Description |
|---|---|---|
| string | musicTrackId | The id of the music track to play. |
| bool | loop | Whether the track should loop when it finishes. |
| MusicPlayerTransitionType | transitionType | Transition strategy applied when moving from the current track to the new one. |
| float | transitionDuration | Duration of the transition in seconds. Ignored for CUT. |
ResumeSong()
Resumes playback of the previously paused music track.
Sets the playing state to true and resumes all paused audio clips.
Continues music playback from the position where it was paused.
Declaration
public virtual void ResumeSong()
SetMusicTracks(List<MusicTrack>)
Sets the complete music tracks collection for the player.
Replaces the current playlist with the provided music tracks collection.
Resets the playlist and allows for dynamic music library updates.
Declaration
public virtual void SetMusicTracks(List<MusicTrack> musicTracks)
Parameters
| Type | Name | Description |
|---|---|---|
| List<MusicTrack> | musicTracks | The new collection of music tracks to use as the playlist. |
StopSong()
Stops the currently playing music track completely and cancels any in-flight transition.
Sets playing state to false, releases both the current and previous transition sources, and stops all audio clips.
Unlike pause, this resets playback position and requires starting from the beginning when playing again.
Declaration
public virtual void StopSong()
SubscribeToEventDispatcherEvents()
Subscribes to event dispatcher events for music playback control.
Registers handlers for PlayMusicTrackSignal and PlayMusicTrackFromGameSettingsSignal events.
Enables event-driven music control throughout the application.
Declaration
public override void SubscribeToEventDispatcherEvents()
Update()
Unity Update method called every frame to monitor music playback state.
Continuously checks for track ending conditions and handles automatic track transitions.
Ensures seamless music playback and proper playlist progression.
Declaration
public void Update()
ValidateAudioGameSettings(string, UnityAudioGameSettingsDefinition)
Validates audio game settings for music player compatibility.
Ensures that the provided audio game settings are configured correctly for music playback.
Verifies that settings use SELECTABLE value type and that all options reference valid UnityMusicTrackDefinition assets.
Throws exceptions if validation fails to prevent runtime errors.
Declaration
public override void ValidateAudioGameSettings(string id, UnityAudioGameSettingsDefinition audioGameSettings)
Parameters
| Type | Name | Description |
|---|---|---|
| string | id | The identifier for the audio game settings being validated. |
| UnityAudioGameSettingsDefinition | audioGameSettings | The audio game settings definition to validate. |
Exceptions
| Type | Condition |
|---|---|
| Exception | Thrown when audio game settings are invalid or contain invalid references. |