android - 如何在 Android 中获取 spotify 播放器

标签 android spotify spotify-app

在成功授权后,我可以播放硬编码轨道,但它们既不是任何播放器,也不是任何暂停、停止、播放按钮。

我关注了this教程,并做了那里提到的一切。

现在我需要添加 spotify 播放器,但我无法找到与此相关的任何文档。我想我需要自己创建播放器布局,因为播放器 sdk 提供了不同的按钮回调,但是没有什么比为播放器使用预定义布局更好的了。

这是我授权成功后所做的。

        Spotify.getPlayer(playerConfig, this, new SpotifyPlayer.InitializationObserver() {
                @Override
                public void onInitialized(SpotifyPlayer spotifyPlayer) {
                    mPlayer = spotifyPlayer;
                    mPlayer.addConnectionStateCallback(MainActivity.this);
                    mPlayer.addNotificationCallback(MainActivity.this);
                }


@Override
public void onLoggedIn() {
    Log.d("MainActivity", "User logged in");

    mPlayer.playUri(null, "spotify:track:2TpxZ7JUBn3uw46aR7qd6V", 0, 0);
}

最佳答案

如果您遵循了那个教程,您说您已经掌握了该教程,并且如果您能够播放轨道,它似乎可以正常工作,那么您就有了一个 SpotifyPlayer 引用。 getPlayer 方法为您提供了这一点。

虽然 SpotifyPlayer 不是 UI 组件。拥有该播放器 (https://spotify.github.io/android-sdk/player/) 后,您将创建自己的 UI,并将按钮等连接到播放器操作(方法)和事件。

这是一个可能有帮助的示例(不完整或完美!,不全面,但来自一个可能有助于入门的示例项目的快速示例):

public class PlayerActivity extends BaseActivity  {

private ImageView buttonPlayPause;
private TextView labelNowPlaying;

private RecyclerView trackListRecyclerView;
private TrackListAdapter trackListAdapter;
private RecyclerView.LayoutManager trackListLayoutManager;

private Player spotifyPlayer;
private ConnectionStateCallback spotifyConnectionStateCallback;
private Player.NotificationCallback spotifyPlayerNotificationCallback;
private Player.OperationCallback spotifyPlayerOperationCallback;
private String spotifyAccessToken;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_player);

    buttonPlayPause = (ImageView) findViewById(R.id.button_play_pause);
    labelNowPlaying = (TextView) findViewById(R.id.label_now_playing);

    buttonPlayPause.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // toggle spot pause/play
            if (spotifyPlayer == null) {
                Toast.makeText(PlayerActivity.this, "Spotify player not ready", Toast.LENGTH_SHORT).show();
            } else {
                // SpotifyPlayer provides init and connect methods; direct controls (play uri, pause, seek, skip, resume); and state (metadata and playbackstate)
                PlaybackState playbackState = spotifyPlayer.getPlaybackState();
                Log.d(Constants.TAG, "playPause click, playbackState:" + playbackState);
                Metadata metadata = spotifyPlayer.getMetadata();

                if (!playbackState.isPlaying && playbackState.positionMs == 0) {
                    // nothing has been started yet play track 1
                    Track track = trackListAdapter.getFirstTrack();
                    labelNowPlaying.setText(track.getName());
                    spotifyPlayer.playUri(null, track.getUri(), 0, 0);
                    return;
                }

                if (playbackState.isPlaying) {
                    spotifyPlayer.pause(spotifyPlayerOperationCallback);
                    return;
                } 

                if (!playbackState.isPlaying && playbackState.positionMs > 0) {
                    // TODO how to tell if player is paused, idPlaying false and just position != 0? or is there an actual pause state, weird?
                    spotifyPlayer.resume(spotifyPlayerOperationCallback);
                    return;
                } 

                // get here it's weird
                Log.d(Constants.TAG, "error unexepected playback state:" + playbackState);
                Toast.makeText(PlayerActivity.this, "Spotify playback state weird:" + playbackState, Toast.LENGTH_LONG).show();                    
            }
        }
    });

    spotifyPlayerNotificationCallback = new Player.NotificationCallback() {
        @Override
        public void onPlaybackEvent(PlayerEvent playerEvent) {
            Log.d(Constants.TAG, "Spotify player notif callback: playback event: " + playerEvent.name());
            handleSpotifyEvent(playerEvent);
        }

        @Override
        public void onPlaybackError(Error error) {
            Log.d(Constants.TAG, "Spotify player notif callback: playback error: " + error.name());
            handleSpotifyError(error);
        }
    };

    // recycler view
    List<Track> playList = application.getPlaylist();
    trackListRecyclerView = (RecyclerView) findViewById(R.id.track_list_recycler);
    trackListRecyclerView.setHasFixedSize(true);
    trackListLayoutManager = new LinearLayoutManager(this);
    trackListRecyclerView.setLayoutManager(trackListLayoutManager);
    trackListAdapter = new TrackListAdapter(PlayerActivity.this, playList);
    trackListRecyclerView.setAdapter(trackListAdapter);

    // get track list click events as observable
    trackListAdapter.asObservable().subscribe(new Action1<Track>() {
        @Override
        public void call(Track track) {
            // TODO make other adapter list items not clickable until one is processed?
            labelNowPlaying.setText(track.getName());
            spotifyPlayer.playUri(null, track.getUri(), 0, 0);
        }
    });

    // spotify player callback
    spotifyConnectionStateCallback = new ConnectionStateCallback() {

        @Override
        public void onLoggedIn() {
            Log.d(Constants.TAG, "Spotify connection callback: User logged in");
        }

        @Override
        public void onLoggedOut() {
            Log.d(Constants.TAG, "Spotify connection callback: user logged out");
        }

        @Override
        public void onLoginFailed(Error e) {
            Log.d(Constants.TAG, "Spotify connection callback: login failed: " + e.toString());
        }

        @Override
        public void onTemporaryError() {
            Log.d(Constants.TAG, "Spotify connection callback: temp error occurred");
        }

        @Override
        public void onConnectionMessage(String message) {
            Log.d(Constants.TAG, "Spotify connection callback: connection message: " + message);
        }
    };

    spotifyPlayerOperationCallback = new Player.OperationCallback() {
        @Override
        public void onSuccess() {
            Log.d(Constants.TAG, "Spotify operation callback: success");
        }

        @Override
        public void onError(Error error) {
            Log.d(Constants.TAG, "Spotify operation callback: error " + error.name());
            Toast.makeText(PlayerActivity.this, "Spotify op error: " + error.name(), Toast.LENGTH_SHORT).show();
        }
    };

    spotifyAccessToken = application.getSpotifyAccessToken();
    initSpotifyPlayer();
}

@Override
protected void onDestroy() {
    Spotify.destroyPlayer(this);
    super.onDestroy();
}

//
// private
//

//
// SPOT
//

private void initSpotifyPlayer() {

    Log.d(Constants.TAG, "initSpotifyPlayer");

    if (spotifyAccessToken == null) {
        Toast.makeText(this, "Spotify access token not present, cannot continue", Toast.LENGTH_LONG).show();
        return;
    }

    Config playerConfig = new Config(this, spotifyAccessToken, application.getSpotifyClientId());
    Spotify.getPlayer(playerConfig, this, new SpotifyPlayer.InitializationObserver() {
        @Override
        public void onInitialized(SpotifyPlayer player) {
            spotifyPlayer = player;
            spotifyPlayer.addConnectionStateCallback(spotifyConnectionStateCallback);
            spotifyPlayer.addNotificationCallback(spotifyPlayerNotificationCallback);
        }

        @Override
        public void onError(Throwable throwable) {
            Log.e(Constants.TAG, "Could not initialize player: " + throwable.getMessage());
        }
    });
}

private void handleSpotifyEvent(final PlayerEvent playerEvent) {
    Log.d(Constants.TAG, "Spotify playerEvent:" + playerEvent.name());

    switch (playerEvent) {

        case kSpPlaybackEventAudioFlush:
            break;
        case kSpPlaybackNotifyAudioDeliveryDone:
            break;
        case kSpPlaybackNotifyBecameActive:
            break;
        case kSpPlaybackNotifyBecameInactive:
            break;
        case kSpPlaybackNotifyContextChanged:
            break;
        case kSpPlaybackNotifyLostPermission:
            Toast.makeText(PlayerActivity.this, "Spotify player perms lost (logged in elsewhere?)", Toast.LENGTH_LONG).show();
            buttonPlayPause.setImageResource(android.R.drawable.ic_media_play);
            startActivity(new Intent(PlayerActivity.this, MainActivity.class));
            break;
        case kSpPlaybackNotifyMetadataChanged:
            break;
        case kSpPlaybackNotifyNext:
            break;
        case kSpPlaybackNotifyPause:
            buttonPlayPause.setImageResource(android.R.drawable.ic_media_play);                
            break;
        case kSpPlaybackNotifyPlay:
            buttonPlayPause.setImageResource(android.R.drawable.ic_media_pause);
            // TODO get current playing track here? 
            //labelNowPlaying.setText(spotifyPlayer.getMetadata().currentTrack.
            break;
        case kSpPlaybackNotifyPrev:
            break;
        case kSpPlaybackNotifyRepeatOff:
            break;
        case kSpPlaybackNotifyRepeatOn:
            break;
        case kSpPlaybackNotifyShuffleOff:
            break;
        case kSpPlaybackNotifyShuffleOn:
            break;
        case kSpPlaybackNotifyTrackChanged:
            break;
        case kSpPlaybackNotifyTrackDelivered:
            break;

        default:
            break;
    }
}

private void handleSpotifyError(final Error error) {
    Log.e(Constants.TAG, "Spotify Error:" + error.name());

    switch (error) {
        // corrupt track, add is playing, need perms, travel restriction, etc
        default:
            break;
    }
}

}

关于android - 如何在 Android 中获取 spotify 播放器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47903614/

相关文章:

android - 在哪里放置文件的 Chaquopy 包/模块

Android模拟器,用手掌盖住屏幕变暗

applescript - 在 Applescript 中监控 Spotify 轨道变化?

spotify - 从 Spotify 应用程序获取数据 (Windows/Mac)

java - 最短编辑距离?我需要它吗?

java - 将 String.xml 中的数组字符串添加到 ArrayList

excel - Spotify - 如何创建包含艺术家某些专辑的播放列表

audio - 使用Spotify API增强播放

ios - 歌曲仅在高级 Spotify 帐户中播放