-
-
Notifications
You must be signed in to change notification settings - Fork 86
/
SoundPlayerManager.kt
404 lines (352 loc) · 12.8 KB
/
SoundPlayerManager.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package com.github.ashutoshgngwr.noice.engine
import android.util.Log
import androidx.media3.common.AudioAttributes
import androidx.media3.common.C
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import kotlin.properties.Delegates.observable
import kotlin.time.Duration
/**
* [SoundPlayerManager] is responsible for managing the state and lifecycle of [SoundPlayer]
* instances for each and every sound. The class provides methods to set fade-in and fade-out
* durations, enable/disable premium segments, set the audio bitrate, and adjust the volumes of all
* sound players. It also provides methods to play, stop and set volumes of individual sounds, play
* presets, and pause, resume and stop all sounds.
*
* [SoundPlayerManager.State] enum represents playback states of the sound player manager. The
* manager initialises in [SoundPlayerManager.State.STOPPED] state. There's no terminal state in
* manager's lifecycle. [SoundPlayerManager.State.PAUSING] and [SoundPlayerManager.State.STOPPING]
* are special states that the manager temporarily assumes to indicate that all sounds are either in
* pausing or in stopping states.
*/
class SoundPlayerManager(
private var soundPlayerFactory: SoundPlayer.Factory,
private val audioFocusManager: AudioFocusManager,
private val listener: Listener,
) : AudioFocusManager.Listener {
private var fadeInDuration = Duration.ZERO
private var fadeOutDuration = Duration.ZERO
private var isPremiumSegmentsEnabled = false
private var audioBitrate = "128k"
private var audioAttrs = DEFAULT_AUDIO_ATTRIBUTES
private var volume = 1F
private var shouldResumeOnFocusGain = false
private val soundPlayers = ConcurrentHashMap<String, SoundPlayer>()
private val soundPlayerVolumes = ConcurrentHashMap<String, Float>()
var state by observable(State.STOPPED) { _, oldValue, newValue ->
if (oldValue != newValue) listener.onSoundPlayerManagerStateChange(newValue)
}
private set
init {
audioFocusManager.setAudioAttributes(audioAttrs)
audioFocusManager.setListener(this)
}
override fun onAudioFocusGained() {
if (shouldResumeOnFocusGain) {
shouldResumeOnFocusGain = false
resume()
}
}
override fun onAudioFocusLost(transient: Boolean) {
if (state == State.PAUSED || state == State.STOPPED) {
return
}
pause(true)
shouldResumeOnFocusGain = transient
}
/**
* Sets the duration for fading in sounds.
*/
fun setFadeInDuration(duration: Duration) {
fadeInDuration = duration
soundPlayers.values.forEach { it.setFadeInDuration(duration) }
}
/**
* Sets the duration for fading out sounds.
*/
fun setFadeOutDuration(duration: Duration) {
fadeOutDuration = duration
soundPlayers.values.forEach { it.setFadeOutDuration(duration) }
}
/**
* Sets the premium segments enabled flag of all future [SoundPlayer] instances created by the
* factory, and updates the flag of existing [SoundPlayer] instances.
*/
fun setPremiumSegmentsEnabled(enabled: Boolean) {
if (enabled == isPremiumSegmentsEnabled) {
return
}
isPremiumSegmentsEnabled = enabled
soundPlayers.values.forEach { it.setPremiumSegmentsEnabled(enabled) }
}
/**
* Sets the audio bitrate for streaming sounds.
*
* @param bitrate acceptable values are `128k`, `192k`, `256k` and `320k`.
*/
fun setAudioBitrate(bitrate: String) {
if (bitrate == audioBitrate) {
return
}
audioBitrate = bitrate
soundPlayers.values.forEach { it.setAudioBitrate(bitrate) }
}
/**
* Updates the [AudioAttributes] that the sounds use for playback.
*/
fun setAudioAttributes(attrs: AudioAttributes) {
if (attrs == audioAttrs) {
return
}
audioAttrs = attrs
audioFocusManager.setAudioAttributes(attrs)
soundPlayers.values.forEach { it.setAudioAttributes(attrs) }
}
/**
* Sets the [SoundPlayer.Factory] instance of the [SoundPlayerManager], and recreates all existing
* [SoundPlayer] instances with the new factory.
*/
fun setSoundPlayerFactory(factory: SoundPlayer.Factory) {
if (factory == soundPlayerFactory) {
return
}
soundPlayerFactory = factory
val soundIds = soundPlayers.keys.filterNot { soundId ->
val playerState = soundPlayers[soundId]?.state
playerState == SoundPlayer.State.STOPPING || playerState == SoundPlayer.State.STOPPED
}
val pausedSoundIds = soundIds.filter { soundId ->
val playerState = soundPlayers[soundId]?.state
playerState == SoundPlayer.State.PAUSING || playerState == SoundPlayer.State.PAUSED
}.toHashSet()
stop(true)
soundPlayers.clear()
soundIds.forEach { soundId ->
if (soundId in pausedSoundIds) {
initSoundPlayer(soundId)
listener.onSoundStateChange(soundId, soundPlayers.getValue(soundId).state)
} else {
playSound(soundId)
}
}
reconcileState()
}
/**
* Sets a global multiplier used to scale individual volumes of all sounds.
*
* @param volume must be >= 0 and <= 1.
* @throws IllegalArgumentException if the volume is not within the accepted range.
*/
fun setVolume(volume: Float) {
require(volume in 0F..1F) { "volume must be in range [0, 1]" }
this.volume = volume
soundPlayers.forEach { (soundId, player) ->
player.setVolume(volume * (soundPlayerVolumes[soundId] ?: 1F))
}
listener.onSoundPlayerManagerVolumeChange(volume)
}
/**
* Sets the volume of a specific sound identified by the [soundId] parameter.
*
* @param volume must be >= 0 and <= 1.
* @throws IllegalArgumentException if the volume is not within the accepted range.
*/
fun setSoundVolume(soundId: String, volume: Float) {
require(volume in 0F..1F) { "volume must be in range [0, 1]" }
soundPlayerVolumes[soundId] = volume
soundPlayers[soundId]?.setVolume(this.volume * volume)
listener.onSoundVolumeChange(soundId, volume)
}
/**
* Plays the sound identified by the [soundId] parameter. It also resumes all sounds if the
* [SoundPlayerManager] is in the [State.PAUSED].
*/
fun playSound(soundId: String) {
initSoundPlayer(soundId)
val player = soundPlayers.getValue(soundId)
listener.onSoundStateChange(soundId, player.state)
if (!audioFocusManager.hasFocus || state == State.PAUSING || state == State.PAUSED) {
resume()
} else {
player.play()
}
}
/**
* Stops the sound identified by the [soundId] parameter.
*/
fun stopSound(soundId: String) {
soundPlayers[soundId]?.stop(false)
}
/**
* Stops all sounds immediately or with a fade-out effect.
*
* @param immediate whether the stop should be immediate or if the sounds should perform a
* fade-out effect before stopping.
*/
fun stop(immediate: Boolean) {
shouldResumeOnFocusGain = false
soundPlayers.values.forEach { it.stop(immediate) }
}
/**
* Pauses all sounds immediately or with a fade-out effect.
*
* @param immediate whether the pause should be immediate or if the sounds should perform a
* fade-out effect before pausing.
*/
fun pause(immediate: Boolean) {
shouldResumeOnFocusGain = false
val isManagerStopping = this.state == State.STOPPING
soundPlayers.values.forEach { player ->
// If all sounds are stopping, we should transition to pausing state. If only some sounds are
// stopping, we should exempt them from pausing.
if (player.state != SoundPlayer.State.STOPPING || isManagerStopping) {
player.pause(immediate)
}
}
}
/**
* Resumes all sounds that are in [SoundPlayer.State.PAUSED].
*/
fun resume() {
if (audioFocusManager.hasFocus) {
soundPlayers.values.forEach { it.play() }
} else {
shouldResumeOnFocusGain = true
audioFocusManager.requestFocus()
reconcileState()
}
}
/**
* Plays a set of sounds identified by keys in the [soundStates] map and sets their volumes to the
* values in the [soundStates] map, stopping the ones that are not in the [soundStates].
*
* @param soundStates a map of sound ids to their desired volumes.
*/
fun playPreset(soundStates: SortedMap<String, Float>) {
// start needed sounds before stopping the not-needed ones. Because it is possible that all
// sounds need to be stopped before any sound in preset is started. It will cause manager to go
// into stopping state unnecessarily.
val soundsToStop = soundPlayers.keys.subtract(soundStates.keys)
soundStates.forEach { (soundId, volume) ->
setSoundVolume(soundId, volume)
if (soundPlayers[soundId]?.state != SoundPlayer.State.PLAYING) {
playSound(soundId)
}
}
soundsToStop.forEach(this::stopSound)
}
/**
* @return a map of ids of the currently active (buffering, playing, pausing or paused) sounds and
* their corresponding volumes.
*/
fun getCurrentPreset(): SortedMap<String, Float> {
return soundPlayers
.filterValues { state == State.STOPPING || (it.state != SoundPlayer.State.STOPPING && it.state != SoundPlayer.State.STOPPED) }
.mapValues { soundPlayerVolumes[it.key] ?: 1F }
.toSortedMap()
}
private fun initSoundPlayer(soundId: String) {
if (soundPlayers.containsKey(soundId) && soundPlayers[soundId]?.state != SoundPlayer.State.STOPPED) {
return // a sound player already exists and is not in its terminal state.
}
soundPlayers[soundId] = soundPlayerFactory.buildPlayer(soundId).also { p ->
p.setFadeInDuration(fadeInDuration)
p.setFadeOutDuration(fadeOutDuration)
p.setPremiumSegmentsEnabled(isPremiumSegmentsEnabled)
p.setAudioBitrate(audioBitrate)
p.setAudioAttributes(audioAttrs)
p.setVolume(volume * (soundPlayerVolumes[soundId] ?: 1F))
p.setStateChangeListener { onSoundPlayerStateChange(soundId, it) }
}
}
private fun onSoundPlayerStateChange(soundId: String, state: SoundPlayer.State) {
Log.d(LOG_TAG, "onSoundPlayerStateChange: $soundId=$state")
if (state == SoundPlayer.State.STOPPED) {
soundPlayers.remove(soundId)
}
if (soundPlayers.isEmpty()) {
audioFocusManager.abandonFocus()
}
reconcileState()
listener.onSoundStateChange(soundId, state)
}
private fun reconcileState() {
val soundPlayerStates = soundPlayers.values.map { it.state }
state = when {
soundPlayerStates.isEmpty() -> State.STOPPED
soundPlayerStates.all { it == SoundPlayer.State.STOPPING } -> State.STOPPING
soundPlayerStates.all { it == SoundPlayer.State.PAUSED } -> State.PAUSED
// some players may be stopping during the pause transition.
soundPlayerStates.all { it == SoundPlayer.State.PAUSING || it == SoundPlayer.State.PAUSED || it == SoundPlayer.State.STOPPING } -> State.PAUSING
else -> State.PLAYING
}
}
companion object {
private const val LOG_TAG = "SoundPlayerManager"
/**
* Audio attributes that the [SoundPlayerManager] should use to perform its playback on the
* music audio stream.
*/
val DEFAULT_AUDIO_ATTRIBUTES: AudioAttributes = AudioAttributes.Builder()
.setContentType(C.AUDIO_CONTENT_TYPE_MUSIC)
.setUsage(C.USAGE_MEDIA)
.setAllowedCapturePolicy(C.ALLOW_CAPTURE_BY_SYSTEM)
.build()
/**
* Audio attributes that the [SoundPlayerManager] should use to perform its playback on the
* alarm audio stream.
*/
val ALARM_AUDIO_ATTRIBUTES: AudioAttributes = AudioAttributes.Builder()
.setContentType(C.AUDIO_CONTENT_TYPE_MUSIC)
.setUsage(C.USAGE_ALARM)
.setAllowedCapturePolicy(C.ALLOW_CAPTURE_BY_SYSTEM)
.build()
}
/**
* Represents the current playback state of the [SoundPlayerManager].
*/
enum class State {
/**
* At least one sound in the manager is currently in buffering or playing state.
*/
PLAYING,
/**
* All sounds in the manager are currently in pausing state.
*/
PAUSING,
/**
* All sounds in the manager are currently in paused state.
*/
PAUSED,
/**
* All sounds in the manager are currently in stopping state.
*/
STOPPING,
/**
* All sounds in the manager are currently in stopped state.
*/
STOPPED,
}
/**
* A listener interface for observing changes in the playback state of a [SoundPlayerManager] and
* the playback state and volume [SoundPlayer]s it manages.
*/
interface Listener {
/**
* Invoked when the playback state of the sound player manager changes
*/
fun onSoundPlayerManagerStateChange(state: State)
/**
* Invoked when the volume of the sound player manager changes.
*/
fun onSoundPlayerManagerVolumeChange(volume: Float)
/**
* Invoked when the state of a sound player changes.
*/
fun onSoundStateChange(soundId: String, state: SoundPlayer.State)
/**
* Invoked when the volume of a sound player changes.
*/
fun onSoundVolumeChange(soundId: String, volume: Float)
}
}