Skip to content

About

Android library (SoundKit) for sound effects and background music. Wraps SoundPool and MediaPlayer with audio focus, fades, volume control and lifecycle handling. Published on JitPack.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

SoundKit

A lightweight, lifecycle-aware Android sound library for sound effects and background music. It wraps SoundPool and MediaPlayer in one simple API. Written in Kotlin, with a UI-agnostic SoundManager that works from Views or Compose; the bundled demo app uses XML, View Binding and Material 3.

Features

  • Play short sound effects by name (click, success, error, notification)
  • Play background music: play / pause / resume / stop
  • Play any source: a bundled res/raw resource or a file the user picks (content Uri)
  • Looping music
  • Independent music & SFX volume, plus mute / unmute
  • Pitch control for effects (0.5x to 2x), per-call or global
  • Fade in / out for music (tunable ramp)
  • Seek plus position / duration, isMusicPlaying, stopAll
  • Audio focus: auto pause, resume and duck for calls & other apps
  • Lifecycle-aware: auto-pause on stop, auto-release on destroy (no leaks)
  • Observable state through a single listener
  • Zero runtime permissions

Screenshots

Light theme

Light, top

Light, scrolled

Dark theme

Dark, top

Dark, scrolled

Installation

Add the JitPack repository to your settings.gradle.kts:

dependencyResolutionManagement {
    repositories {
        maven { url = uri("https://jitpack.io") }
    }
}

Add the dependency (bump the version to match the GitHub release tag you create):

dependencies {
    implementation("com.github.RotemBar18.SoundManagerModule:soundlibrary:1.0.0")
}

Then add your audio files to the consuming app's res/raw/ (lowercase names, e.g. click.wav, music.mp3). No manifest entries and no permissions are required.

Quick Start

val sound = SoundManager(context)
lifecycle.addObserver(sound)            // auto-pause on stop, auto-release on destroy

// sound effects: register once, then play by key
sound.registerSound("click", R.raw.click)
sound.playSound("click")

// background music
sound.setFadeEnabled(true)
sound.playMusic(R.raw.music, loop = true)

Data Classes

SoundManager

SoundManager(
    context: Context        // any Context; the applicationContext is kept internally
)

SoundState

The immutable snapshot delivered to your Listener on every change.

SoundState(
    musicState = MusicState.IDLE,   // current music state
    musicVolume = 1.0f,             // music volume, 0f..1f
    sfxVolume = 1.0f,               // effect volume, 0f..1f
    isMuted = false,                // everything muted
    isLooping = true,               // music loops
    sfxRate = 1.0f,                 // global effect pitch/rate, 0.5f..2f
    isFadeEnabled = false           // music fades in/out
)

MusicState

enum class MusicState {
    IDLE,       // nothing started yet, or resources released
    PLAYING,    // a track is playing
    PAUSED,     // a track is started but paused
    STOPPED     // playback stopped, or a non-looping track finished
}

SoundManager.Listener

interface Listener {
    fun onStateChanged(state: SoundState)   // called on every state/settings change
}

API Reference

All functionality lives on SoundManager. Every method below is public; all other classes are internal.

Sound Effects

Method Parameters Description
registerSound key: String, @RawRes resId: Int Pre-load one effect under key (call once). Re-registering a key is ignored.
registerSounds sounds: Map<String, Int> Pre-load several effects at once.
playSound key: String, rate: Float = sfxRate Play an effect. No-op while muted. rate is pitch/speed (0.5 to 2.0).
setSfxRate rate: Float Global effect pitch/rate for later playSound calls (0.5 to 2.0).

Background Music

Method Parameters Description
playMusic @RawRes resId: Int, loop: Boolean = true Start/restart music from a bundled resource.
playMusic uri: Uri, loop: Boolean = true Start/restart music from a content Uri (a picked file).
pauseMusic none Pause (user) and abandon audio focus.
resumeMusic none Re-request focus and resume.
stopMusic none Stop and release the current track.
setLooping loop: Boolean Toggle looping for current & future tracks.

Transport & Query

Method Returns Description
seekToMusic(positionMs: Int) none Jump to positionMs (clamped to 0 or more; no-op if nothing loaded).
getMusicPositionMs() Int Current position in ms (0 if nothing loaded).
getMusicDurationMs() Int Track length in ms (0 if nothing loaded).
isMusicPlaying() Boolean true only while actively playing.
stopAll() none Stop the music and all sound effects.

Volume & Mute

Method Parameters Description
setMusicVolume volume: Float (0 to 1) Music volume, applied immediately.
setSfxVolume volume: Float (0 to 1) Effect volume, applied on the next playSound.
setMuted muted: Boolean Mute/unmute everything (music goes to 0 but keeps playing; effects skipped).
toggleMute none Flip the mute state.
isMuted returns Boolean Current mute state.

Fade

Method Parameters Default Description
setFadeEnabled enabled: Boolean off Enable/disable fading using a 600 ms ramp.
setFadeDurationMs ms: Long 0 Ramp length in ms; 0 disables fading.

State & Lifecycle

Method Parameters Description
setListener listener: Listener? Observe state changes; the current state is pushed immediately. null to clear.
currentState returns SoundState Immutable snapshot of all settings + music state.
release none Free every native audio resource. Do not reuse afterwards.
onStop(owner) / onDestroy(owner) LifecycleOwner DefaultLifecycleObserver hooks for auto-pause / auto-release.

Examples

Sound Effects

sound.registerSounds(mapOf("click" to R.raw.click, "ok" to R.raw.success))
sound.playSound("click")
sound.playSound("click", rate = 1.5f)   // higher pitch, one-off
sound.setSfxRate(0.8f)                   // pitch every effect down a little

Background Music

sound.playMusic(R.raw.music, loop = true)
sound.pauseMusic()
sound.resumeMusic()
sound.stopMusic()

Pick a File From the Device

private val pickAudio =
    registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
        if (uri != null) sound.playMusic(uri, loop = true)   // no permissions needed
    }

chooseButton.setOnClickListener { pickAudio.launch("audio/*") }

Seek Bar / Progress

// update a 0..1 progress slider (poll on a ~250 ms tick)
val duration = sound.getMusicDurationMs()
if (duration > 0) slider.value = sound.getMusicPositionMs().toFloat() / duration

// seek when the user drags
slider.addOnChangeListener { _, value, fromUser ->
    if (fromUser) sound.seekToMusic((value * sound.getMusicDurationMs()).toInt())
}

Volume, Mute & Pitch

sound.setMusicVolume(0.5f)
sound.setSfxVolume(0.8f)
sound.toggleMute()

Fade In / Out

sound.setFadeEnabled(true)     // 600 ms ramp on play/resume (up) and pause/stop (down)
sound.setFadeDurationMs(1000)  // custom ramp length

Observe State

sound.setListener(object : SoundManager.Listener {
    override fun onStateChanged(state: SoundState) {
        statusLabel.text = state.musicState.name
        // state.musicVolume, state.sfxVolume, state.isMuted, state.isLooping,
        // state.sfxRate, state.isFadeEnabled
    }
})

Lifecycle (no manual cleanup)

val sound = SoundManager(this)
lifecycle.addObserver(sound)   // onStop calls pauseMusic(), onDestroy calls release()

Requirements

  • Min SDK: 28 (the modern AudioFocusRequest API requires API 26+)
  • compileSdk / targetSdk: 36
  • Language: Kotlin (AGP 9 built-in Kotlin)
  • Build: Android Gradle Plugin 9.1.1, Gradle 9.3.1, Java 11
  • Demo app only: Material Components 1.13
  • Runtime permissions: none

About

Android library (SoundKit) for sound effects and background music. Wraps SoundPool and MediaPlayer with audio focus, fades, volume control and lifecycle handling. Published on JitPack.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages