Search code examples
androidandroid-mediaplayerspotifysessionidvisualizer

Android Visualizer won't pick up audio from Spotify streaming music


I'm making an Android audio visualizer app for streaming Spotify music. I'm using Spotify's android-streaming-sdk which creates a local service (no need to have the Spotify app installed) and it plays music from within the app. I'm having a difficult time getting Androids Visualizer library to pick up any audio from Spotify (it works fine if I use a local .mp3 file).

//Start playing spotify track
player.playUri(MainActivity.operationCallback, 
               VisualizerModel.getInstance().getTrackURI(), 0, 0);

.... other code ....

MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

int audioSessionId = mediaPlayer.getAudioSessionId();

visualizer = new Visualizer(audioSessionId);
visualizer.setCaptureSize(audioSampleSize); 
visualizer.setDataCaptureListener(this, Visualizer.getMaxCaptureRate(), true, true);

visualizer.setEnabled(true);

If I run this, everything compiles and runs okay, but the visualizer does not pick up any audio. This makes me thing that the audio sessionId is not the same one as Spotify is playing on. However, if I switch the audioSessionId to 0 (which should listen to all the audio sessions mixed from what I understand) it crashes with this error:

E/AudioEffect: set(): AudioFlinger could not create effect, status: -1
E/visualizers-JNI: Visualizer initCheck failed -3
E/Visualizer-JAVA: Error code -3 when initializing Visualizer.

According to their documentation that error means: Operation failed due to bad object initialization.

I'm targetting API 24 (Android 7.0).

Please let me know if you have suggestions or an alternative to using Android's Visualizer library. I feel like my main problem is that I'm not sure how to find the audioSessionId that Spotify is playing on, and because Spotify's android-streaming-sdk is in beta (and not mentioned on their website) there is virtually no documentation on it from what I can see on Github.

Thank you for taking the time to read my issue!


Solution

  • I was facing the same error. Adding "android.permission.RECORD_AUDIO" to manifest and requesting for runtime permissions fixed the issue.

    to protect privacy of certain audio data (e.g voice mail) the use of the visualizer requires the permission android.permission.RECORD_AUDIO

    Also

    Creating a Visualizer on the output mix (audio session 0) requires permission Manifest.permission.MODIFY_AUDIO_SETTINGS

    Android docs for Visualizer class