javagluon-mobile

How to play audio using the device's volume?


The Audio interface allows to set its volume, but apps usually use the Media or Notifications volumes on Android. In a Gluon Mobile app, pressing the volume keys does nothing, while in other apps the device's volume changes.

Tested on Android 8 and 12 using Attach version 4.0.15.

Is there a way to play audio using the device's volume settings and allow the user to adjust the volume from within the device?


Solution

  • There seems to be no proper way to do this. Using the VideoService it's possible to change the volume of the device, but only while audio is playing, which requires the user to be ready to do so for short audio clips.

    The VideoService also does not support playing a single file out of a playlist. The only solution I found was switching the playlist to a single audio clip whenever it's required to be played and isn't played already:

    class MobileNotifier {
    
        private static final String SMALL_BEEP_PATH = "/sounds/SmallBeep.wav";
        private static final String BIG_BEEP_PATH = "/sounds/BigBeep.wav";
    
        VideoService service;
        
        private MobileNotifier(VideoService service) {
            this.service = service;
            service.getPlaylist().add(SHORT_BEEP_PATH);
        }
        
        public void play(Alert alert) {
            switch (alert) {
                case SMALL -> {
                    if (service.statusProperty().get() != Status.PLAYING || !SMALL_BEEP_PATH.equals(service.getPlaylist().get(0))) {
                        service.stop();
                        service.getPlaylist().set(0, SMALL_BEEP_PATH);
                        service.play();
                    }
                }
                case BIG -> {
                    if (service.statusProperty().get() != Status.PLAYING || !BIG_BEEP_PATH.equals(service.getPlaylist().get(0))) {
                        service.stop();
                        service.getPlaylist().set(0, LONG_BEEP_PATH);
                        service.play();
                    }
                }
            };
        }
    
    }