如何根据铃声音量设置 android MediaPlayer 音量?

How to set android MediaPlayer volume according to ringtone volume?

如何根据铃声音量设置MediaPlayer音量?

我用了这个方法,但是没用:

        MediaPlayer player = MediaPlayer.create(MyActivity.this, R.raw.sound);
        AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int currentVolume = audio.getStreamVolume(AudioManager.RINGER_MODE_NORMAL);

        player.setVolume(currentVolume, currentVolume);

试一试:

AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int currentVolume = audio.getStreamVolume(AudioManager.STREAM_RING);

您应该使用 setAudioStreamType() to set which audio stream you want to play your audio over - this automatically uses the volume of the selected stream. For example, if you want your audio to play at the same volume as a notification would, you could use AudioManager.STREAM_NOTIFICATION:

而不是调整音量
mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);

尝试在 AudioManager.STREAM_NOTIFICATION 或 AudioManager.STREAM_RING 上播放时没有发出任何声音。我必须经历 AudioManager.STREAM_MUSIC。使用 Android: MediaPlayer setVolume function 上的 ssuukk 的想法,我编写了以下有效的代码:

AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
int volume_level1= am.getStreamVolume(AudioManager.STREAM_RING);
int maxVolume=am.getStreamMaxVolume(AudioManager.STREAM_RING);
final MediaPlayer mp1 = MediaPlayer.create(context, R.raw.notification_delivery);
mp1.setAudioStreamType(AudioManager.STREAM_MUSIC);
float log1=(float)(1-Math.log(maxVolume-volume_level1)/Math.log(maxVolume));
mp1.setVolume(log1,log1);

您可以尝试如下:

 AudioAttributes audioAttributes = new AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN)
            .setLegacyStreamType(AudioManager.STREAM_RING)
            .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE).build();
    int s = audioManager.generateAudioSessionId();
    mediaPlayer = MediaPlayer.create(context, R.raw.default_ring,audioAttributes,s);
    mediaPlayer.setLooping(true);
    mediaPlayer.start();

您可以在setLegacyStreamType()中传递所需的流类型。如果您喜欢上面的内容,您的媒体播放器 voulme 将遵循在音频属性中传递给 setLegacyStreamType() 方法的流类型音量。