title: Alsa - setting volume in an app works different when it is run as a service
body: <p>I have an app which is using Alsa to play sounds. Below I show fragments of my code. The problem is that if my software is run as a systemd service, the range in the stVolume method is between 0 and 31. When I run my software as a standard application from the command line, the range is between 0 and 65536. In the first scenario the sound is very distorted and loud, I hear noise. It is much better in the second scenario. What is the reason? Why the same code run in a different way seems to use Alsa/sound card differently? Why Alsa is returning different range in both cases?</p>
  <pre><code>void init() {
      snd_mixer_open(&amp;mMixer.handle, 0);
      snd_mixer_attach(mMixer.handle, mCardName);
      snd_mixer_selem_register(mMixer.handle, NULL, NULL);
      snd_mixer_load(mMixer.handle);
  
      snd_mixer_selem_id_alloca(&amp;mMixer.sid);
      snd_mixer_selem_id_set_index(mMixer.sid, 0);
      snd_mixer_selem_id_set_name(mMixer.sid, mMixerName);
      mMixer.slider = snd_mixer_find_selem(mMixer.handle, mMixer.sid);
  }
  </code></pre>
  <p>where mMixer is a following struct:</p>
  <pre><code>struct {
      snd_mixer_t *handle;
      snd_mixer_selem_id_t *sid;
      snd_mixer_elem_t *slider;
  } mMixer;
  </code></pre>
  <p>and mCardName and mMixerName are:</p>
  <pre><code>const char *mCardName = &quot;default&quot;;
  const char *mMixerName = &quot;Master&quot;;
  </code></pre>
  <p>When I want to play sound, I invoke the following method:</p>
  <pre><code>void on() {
      try {
          // open audio device
          int err = snd_pcm_open(&amp;mHandle, mCardName,
              SND_PCM_STREAM_PLAYBACK,
              SND_PCM_NONBLOCK);
          
          if (err &lt; 0)
              throw std::runtime_error(snd_strerror(err));
  
          // configure audio
          g_assert_nonnull(mHandle);
  
          err = snd_pcm_set_params(mHandle,
              SND_PCM_FORMAT_U8,
              SND_PCM_ACCESS_RW_INTERLEAVED,
              1,         // channels
              SAMPLE_RATE,     // sample rate
              1,         // soft resample allowed
              500000);   // latency (in us)
  
          if (err &lt; 0)
              throw std::runtime_error(snd_strerror(err));
      } catch(std::runtime_error &amp;e) {
          g_printerr(&quot;Can't configure audio: %s\n&quot;, e.what());
      }
  }
  </code></pre>
  <p>and then I set the volume:</p>
  <pre><code>void setVolume(unsigned volume) {
      long min = 0, max = 0;      // NOLINT (type required by ALSA
      snd_mixer_selem_get_playback_volume_range(mMixer.slider, &amp;min, &amp;max);
      snd_mixer_selem_set_playback_volume_all(mMixer.slider, volume * max / 100);
  
      g_warning(&quot;FHR probe volume %ld. Min: %ld, Max: %ld&quot;, volume * max / 100, min, max);
  }
  </code></pre>