How to shut off the sound MediaRecorder plays when the state changes

前端 未结 5 1754
自闭症患者
自闭症患者 2020-12-23 23:20

My Android application uses MediaRecorder on a SurfaceHolder to show a live preview of what the camera is capturing. Every time the user presses the REC button on the app, t

5条回答
  •  轮回少年
    2020-12-24 00:04

    Following on from @wired00's answer, the code can be simplified as follows:

    private void setMuteAll(boolean mute) {
        AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    
        int[] streams = new int[] { AudioManager.STREAM_ALARM,
            AudioManager.STREAM_DTMF, AudioManager.STREAM_MUSIC,
            AudioManager.STREAM_RING, AudioManager.STREAM_SYSTEM,
            AudioManager.STREAM_VOICE_CALL };
    
        for (int stream : streams)
            manager.setStreamMute(stream, mute);
    }
    

    This works fine for now but if more streams are introduced in the future, this method may need updating. A more robust approach (though perhaps overkill) is to use reflection to get all the STREAM_* static fields:

    List streams = new ArrayList();
    Field[] fields = AudioManager.class.getFields();
    for (Field field : fields) {
         if (field.getName().startsWith("STREAM_")
             && Modifier.isStatic(field.getModifiers())
             && field.getType() == int.class) {
             try {
                 Integer stream = (Integer) field.get(null);
                 streams.add(stream);
             } catch (IllegalArgumentException e) {
                  // do nothing
             } catch (IllegalAccessException e) {
                 // do nothing
            }
        }
    }
    

    Interestingly, there seem to be some streams that are not documented, namely STREAM_BLUETOOTH_SCO, STREAM_SYSTEM_ENFORCED and STREAM_TTS. I'm guessing/hoping there's no harm in muting these too!

提交回复
热议问题