问题描述
我正在尝试获取 Spotify 音乐流的音量值。 当 Spotify 从 Android 设备播放音乐或 Android 设备连接到蓝牙扬声器时,我可以让它抛出 STREAM_MUSIC。
但是当我从 Android 设备流式传输到 Smart TV/TV Streamer 上的 Spotify 应用程序时,Android 正在创建一个名为“Spotify”的新音量流(如图所示) 我怎样才能得到这个值?
Picture of Volume Streams on my Android device
请帮助我了解如何获得此流的音量.. 谢谢!
解决方法
其实,太难了。
首先,你必须使用 MediaSessionManager.getActiveSessions https://developer.android.com/reference/android/media/session/MediaSessionManager#getActiveSessions(android.content.ComponentName)
但它需要 NotificationListenerService。 请参阅 https://developer.android.com/reference/android/service/notification/NotificationListenerService https://github.com/codechacha/NotificationListener
MyNotificationService.java
public class MyNotificationService extends NotificationListenerService {
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
super.onNotificationRemoved(sbn);
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
super.onNotificationPosted(sbn);
}
}
AndroidManifest.xml
<service
android:name=".MyNotificationService"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
<meta-data
android:name="android.service.notification.default_filter_types"
android:value="1,2">
</meta-data>
</service>
请求权限
if (!permissionGrantred()) {
Intent intent = new Intent(
"android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
}
private boolean permissionGrantred() {
Set<String> sets = NotificationManagerCompat.getEnabledListenerPackages(this);
if (sets != null && sets.contains(getPackageName())) {
return true;
} else {
return false;
}
}
主要代码
MediaSessionManager msm = (MediaSessionManager)getSystemService(Context.MEDIA_SESSION_SERVICE);
ComponentName cn = new ComponentName(this,MyNotificationService.class);
List<MediaController> list = msm.getActiveSessions(cn);
for (MediaController mc : list) {
if (mc.getPackageName().equals("com.spotify.music")) {
int spotifyVolume = mc.getPlaybackInfo().getCurrentVolume();
}
}
或者你可以通过回调得到它
for (MediaController mc : list) {
if (mc.getPackageName().equals("com.spotify.music")) {
mc.registerCallback(new MediaController.Callback() {
@Override
public void onAudioInfoChanged(MediaController.PlaybackInfo info) {
int spotifyVolume = info.getCurrentVolume();
}
});
}
}