【问题标题】:How to get Track Duration for Spotify using Spotipy如何使用 Spotipy 获取 Spotify 的曲目时长
【发布时间】:2021-10-01 01:11:29
【问题描述】:

我一直在使用 Python (Spotipy) 中的 Spotify API,但我不知道如何获取我当前在 Spotify 上播放的曲目的持续时间。 我假设它看起来像这样:

global spotifyObject
trackInfo = spotifyObject.current_user_playing_track()

// would probably look something like this?
trackInfo['duration']

我想这将是一本字典,因为trackInfo['currently_playing_type'] == 'ad' 工作成功。花了一些时间搜索了 Spotipy 文档并猜测了几个关键字,但我仍然没有找到目标。

在 Android Java Spotify API 中,它实际上非常简单:

mSpotifyAppRemote.getPlayerApi()
            .subscribeToPlayerState()
            .setEventCallback(playerState -> {
                final Track track = playerState.track;
                String trackName = track.name;
                // here!
                Long trackDuration = track.duration;
                });

任何帮助表示赞赏:)

谢谢!

【问题讨论】:

  • 试试trackInfo['duration_ms']
  • 它说trackInfo['duration_ms'] 在我打印出来时会抛出KeyError: 'duration_ms'
  • 尝试打印 trackInfo 的内容
  • 它是这么说的^您的建议在访问字典中的嵌套项之前缺少['item']

标签: python spotify spotipy


【解决方案1】:

current_user_playing_track 得到这样的 json 响应:

{
  [...] # [...] means i've deleted a portion to keep the code short
  "progress_ms": 5465,
  "item": {
    "album": [...]
    "artists": [...]
    "disc_number": 1,
    "duration_ms": 163294,
    "explicit": false
    },
  },
  "currently_playing_type": "track",
  "actions": {
    "disallows": {
      "pausing": true,
      "skipping_prev": true
    }
  },
  "is_playing": false
}

我们可以看到"duration_ms" 在"item" 内部,所以要访问它,您需要这样做

trackInfo['item']["duration_ms"]

Spotify 开发者控制台可能对以下情况有所帮助:https://developer.spotify.com/console/get-users-currently-playing-track/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 2017-12-22
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-21
    相关资源
    最近更新 更多