implement music play/pause from ear detection

This commit is contained in:
Kavish Devar
2024-10-11 13:24:05 +05:30
parent 0487ea1f69
commit 81d07a7795
9 changed files with 196 additions and 20 deletions

View File

@@ -0,0 +1,36 @@
package me.kavishdevar.aln
import android.media.AudioManager
import android.view.KeyEvent
class MediaController (private val audioManager: AudioManager){
fun sendPause() {
if (audioManager.isMusicActive) {
audioManager.dispatchMediaKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PAUSE))
audioManager.dispatchMediaKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PAUSE))
}
}
fun sendPlay() {
if (!audioManager.isMusicActive) {
audioManager.dispatchMediaKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY))
audioManager.dispatchMediaKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PLAY))
}
}
var initialVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
fun startSpeaking() {
if (!audioManager.isMusicActive) {
// reduce volume to 10% of initial volume
initialVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, (initialVolume * 0.1).toInt(), 0)
}
}
fun stopSpeaking() {
if (!audioManager.isMusicActive) {
// restore initial volume
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, initialVolume, 0)
}
}
}