| import android.content.Context | |
| import android.media.MediaPlayer | |
| import com.your.namespace.R | |
| import kotlinx.coroutines.experimental.launch | |
| import java.util.concurrent.atomic.AtomicLong | |
| import javax.inject.Inject | |
| import javax.inject.Singleton | |
| /** | |
| * Plays picking noises. | |
| */ | |
| @Singleton | |
| class PickingSoundsPlayer @Inject constructor(private val context: Context) { | |
| /** Need to keep a reference to the MediaPlayer or else GC sometimes kills it, cutting off any playing sound */ | |
| private val mediaPlayers = mutableMapOf<Long, MediaPlayer>() | |
| private val counter = AtomicLong() | |
| private val sounds = mapOf( | |
| Sound.PickedItem to R.raw.sound_pick_partial, | |
| Sound.FinishedPickingItem to R.raw.sound_pick_full, | |
| Sound.PickingError to R.raw.sound_pick_error | |
| ) | |
| fun play(sound: Sound) { | |
| val soundId = sounds[sound] ?: throw NullPointerException("Sound $sound doesn't exist!") | |
| val playerIndex = counter.incrementAndGet() | |
| launch { | |
| val mediaPlayer = MediaPlayer.create(context, soundId) | |
| mediaPlayers[playerIndex] = mediaPlayer | |
| mediaPlayer.setOnCompletionListener { | |
| mediaPlayer.release() | |
| mediaPlayers.remove(playerIndex) | |
| } | |
| mediaPlayer.start() | |
| } | |
| } | |
| sealed class Sound { | |
| object PickedItem : Sound() | |
| object FinishedPickingItem : Sound() | |
| object PickingError : Sound() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment