我的应用程序运行时硬件音量按钮不起作用

时间:2013-12-17 19:43:22

标签: java android c++ audio

我一直在研究播放音频的应用。我目前正在播放音频作为STREAM_MUSIC类型的流,这很好用。我希望能够通过设备上的硬件音量控制来控制音量。当我在应用程序中时,硬件按钮不执行任何操作,音量不会更改,并且不会弹出烤面包。然后我按下主页按钮,以便应用程序在后台运行硬件音量按钮。它们仅在我的应用程序在后台运行时才有效。

我尝试在this.setVolumeControlStream(AudioManager.STREAM_MUSIC);方法中使用代码onCreate(),但这并没有改变应用行为,我仍然面临同样的问题。

我也在DROID 2,DROID RAZR,三星Galaxy s3,三星Galaxy s4,联想平板电脑和扎根DROID 2上进行了测试,但它们的行为都相同。

 public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    setVolumeControlStream(audio.STREAM_MUSIC); //this line should set up the hardware
    //buttons to control the volume 
    if (QtApplication.m_delegateObject != null && QtApplication.onCreate != null) {
        QtApplication.invokeDelegateMethod(QtApplication.onCreate, savedInstanceState);
        return;
    }

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    try {
        m_activityInfo = getPackageManager().getActivityInfo(getComponentName(), PackageManager.GET_META_DATA);
    } catch (NameNotFoundException e) {
        e.printStackTrace();
        finish();
        return;
    }

    if (null == getLastNonConfigurationInstance()) {
        // if splash screen is defined, then show it
        if (m_activityInfo.metaData.containsKey("android.app.splash_screen") )
            setContentView(m_activityInfo.metaData.getInt("android.app.splash_screen"));
        startApp(true);
    }
}

1 个答案:

答案 0 :(得分:2)

  

您可能想尝试听音量键按下并以这种方式修改音频流的音量。抵制冲动。 Android提供了方便的setVolumeControlStream()方法,可将音量键按下指向您指定的音频流。

看看这个,我认为这可能会有所帮助:
Use Hardware Volume Keys to Control Your App’s Audio Volume

修改

您需要执行oncreate方法:

 this.setVolumeControlStream(AudioManager.STREAM_MUSIC); //if you use AudioManager.STREAM_MUSIC to load the sound
    soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
      @Override
      public void onLoadComplete(SoundPool soundPool, int sampleId,
          int status) {
        loaded = true;
      }
    });
   soundPool.load(this, R.raw.sound1, 1); // your sound