gpt4 book ai didi

Android MediaRouter 音量事件

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:03:12 26 4
gpt4 key购买 nike

我想在转换时实现在 Youtube 应用程序中看到的音量变化,就像应用程序在后台或锁定屏幕上一样

Like this

private void createSession() {
ComponentName receiver = new ComponentName(getPackageName(), RemoteReceiver.class.getName());
mediaSession = new MediaSessionCompat(this, "PlayerService", receiver, null);
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
mediaSession.setPlaybackState(new PlaybackStateCompat.Builder()
.setState(PlaybackStateCompat.STATE_PLAYING, 0, 1f)
.setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE)
.build());
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.requestAudioFocus(new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
// Ignore
}
}, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
mediaSession.setActive(true);

mediaRouter = MediaRouter.getInstance(this);
mediaRouter.setMediaSessionCompat(mediaSession);
}

现在我得到了像上图一样的 slider ,它响应音量按钮,但我的广播接收器没有收到变化。

最佳答案

您所要做的就是创建一个带有 VolumeProviderCompatMediaSessionCompat

// Here is a volume provider which sets the volume of a remote route.
// Extend VolumeProviderCompat with your own implementation.
public static class RemoteVolume extends VolumeProviderCompat {
public RemoteVolume(MediaRouter.RouteInfo routeInfo) {
super(VolumeProviderCompat.VOLUME_CONTROL_ABSOLUTE, STEPS, 0);
this.stepSize = routeInfo.getVolumeMax() / STEPS;
this.routeInfo = routeInfo;
}

@Override
public void onSetVolumeTo(int volume) {
routeInfo.requestSetVolume(volume * stepSize);
setCurrentVolume(volume);
}

@Override
public void onAdjustVolume(int delta) {
int newVolume = getCurrentVolume() + delta;
routeInfo.requestSetVolume(newVolume * stepSize);
setCurrentVolume(newVolume);
}
}

然后,将 VolumeProviderCompat 连接到您的 MediaSessionCompat:

MediaSessionCompat session = new MediaSessionCompat(context, TAG);

// might need some of these flags
session.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS |
MediaSessionCompat.FLAG_HANDLES_QUEUE_COMMANDS);

// the volume buttons are routed to this session when it is
// active and currently playing
session.setPlaybackState(new PlaybackStateCompat.Builder()
.setState(PlaybackStateCompat.STATE_PLAYING, 0, 1.0f)
.build());

session.setActive(true);

// The media router tries to bind its own VolumeProvider which kinda
// works. We need to unbind the one provided and put ours in.
router.setMediaSessionCompat(session);
session.setPlaybackToRemote(new RemoteVolume(myRemoteRoute));

关于Android MediaRouter 音量事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39957817/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com