or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mdbrowse.mdcache.mdclient.mdindex.mdplayback.mdplaylists.mdpodcasts.mduser-library.md

playback.mddocs/

0

# Playback Control

1

2

Control Spotify playback across user's active devices. Requires Spotify Premium subscription for most playback control features. Provides comprehensive control over playback state, queue management, and device switching.

3

4

## Capabilities

5

6

### Playback Information

7

8

Get current playback state and currently playing content.

9

10

```python { .api }

11

def current_playback(self, market=None, additional_types=None):

12

"""

13

Get current playback information.

14

15

Requires scope: user-read-playback-state

16

17

Args:

18

market (str, optional): ISO 3166-1 alpha-2 country code

19

additional_types (str, optional): Comma-separated list of item types - 'track', 'episode'

20

21

Returns:

22

dict: Playback state object with device, track/episode, progress, shuffle/repeat state, or None if nothing playing

23

"""

24

25

def currently_playing(self, market=None, additional_types=None):

26

"""

27

Get currently playing track or episode.

28

29

Requires scope: user-read-currently-playing

30

31

Args:

32

market (str, optional): ISO 3166-1 alpha-2 country code

33

additional_types (str, optional): Comma-separated list of item types - 'track', 'episode'

34

35

Returns:

36

dict: Currently playing object with basic playback info, or None if nothing playing

37

"""

38

39

def current_user_playing_track(self):

40

"""

41

Get current playing track (deprecated, use currently_playing instead).

42

43

Requires scope: user-read-currently-playing

44

45

Returns:

46

dict: Currently playing track object or None

47

"""

48

```

49

50

### Device Management

51

52

Access and control available playback devices.

53

54

```python { .api }

55

def devices(self):

56

"""

57

Get available devices.

58

59

Requires scope: user-read-playback-state

60

61

Returns:

62

dict: Object containing list of device objects with id, name, type, volume

63

"""

64

65

def transfer_playback(self, device_id, force_play=True):

66

"""

67

Transfer playback to different device.

68

69

Requires scope: user-modify-playback-state

70

Requires: Spotify Premium

71

72

Args:

73

device_id (str or list): Device ID or list of device IDs to transfer to

74

force_play (bool): Ensure playback starts on new device (default: True)

75

76

Returns:

77

None

78

"""

79

```

80

81

### Playback Control

82

83

Start, pause, and navigate through tracks.

84

85

```python { .api }

86

def start_playback(self, device_id=None, context_uri=None, uris=None,

87

offset=None, position_ms=None):

88

"""

89

Start or resume playback.

90

91

Requires scope: user-modify-playback-state

92

Requires: Spotify Premium

93

94

Args:

95

device_id (str, optional): Device ID to start playback on

96

context_uri (str, optional): URI of album, artist, or playlist to play

97

uris (list, optional): List of track/episode URIs to play (max 100)

98

offset (dict, optional): Indicates where to start playback - {'position': 0} or {'uri': 'track_uri'}

99

position_ms (int, optional): Position in milliseconds to start playback

100

101

Returns:

102

None

103

"""

104

105

def pause_playback(self, device_id=None):

106

"""

107

Pause playback.

108

109

Requires scope: user-modify-playback-state

110

Requires: Spotify Premium

111

112

Args:

113

device_id (str, optional): Device ID to pause playback on

114

115

Returns:

116

None

117

"""

118

119

def next_track(self, device_id=None):

120

"""

121

Skip to next track.

122

123

Requires scope: user-modify-playback-state

124

Requires: Spotify Premium

125

126

Args:

127

device_id (str, optional): Device ID to skip on

128

129

Returns:

130

None

131

"""

132

133

def previous_track(self, device_id=None):

134

"""

135

Skip to previous track.

136

137

Requires scope: user-modify-playback-state

138

Requires: Spotify Premium

139

140

Args:

141

device_id (str, optional): Device ID to skip on

142

143

Returns:

144

None

145

"""

146

147

def seek_track(self, position_ms, device_id=None):

148

"""

149

Seek to position in currently playing track.

150

151

Requires scope: user-modify-playback-state

152

Requires: Spotify Premium

153

154

Args:

155

position_ms (int): Position to seek to in milliseconds

156

device_id (str, optional): Device ID to seek on

157

158

Returns:

159

None

160

"""

161

```

162

163

### Playback Settings

164

165

Control shuffle, repeat, and volume settings.

166

167

```python { .api }

168

def shuffle(self, state, device_id=None):

169

"""

170

Toggle shuffle for user's playback.

171

172

Requires scope: user-modify-playback-state

173

Requires: Spotify Premium

174

175

Args:

176

state (bool): True to turn on shuffle, False to turn off

177

device_id (str, optional): Device ID to set shuffle on

178

179

Returns:

180

None

181

"""

182

183

def repeat(self, state, device_id=None):

184

"""

185

Set repeat mode for user's playback.

186

187

Requires scope: user-modify-playback-state

188

Requires: Spotify Premium

189

190

Args:

191

state (str): Repeat mode - 'track', 'context', 'off'

192

device_id (str, optional): Device ID to set repeat on

193

194

Returns:

195

None

196

"""

197

198

def volume(self, volume_percent, device_id=None):

199

"""

200

Set volume for user's playback.

201

202

Requires scope: user-modify-playback-state

203

Requires: Spotify Premium

204

205

Args:

206

volume_percent (int): Volume percentage (0-100)

207

device_id (str, optional): Device ID to set volume on

208

209

Returns:

210

None

211

"""

212

```

213

214

### Queue Management

215

216

Access and modify the playback queue.

217

218

```python { .api }

219

def queue(self):

220

"""

221

Get user's queue.

222

223

Requires scope: user-read-playback-state

224

225

Returns:

226

dict: Queue object with currently_playing and queue arrays

227

"""

228

229

def add_to_queue(self, uri, device_id=None):

230

"""

231

Add track or episode to queue.

232

233

Requires scope: user-modify-playback-state

234

Requires: Spotify Premium

235

236

Args:

237

uri (str): URI of track or episode to add to queue

238

device_id (str, optional): Device ID to add to queue on

239

240

Returns:

241

None

242

"""

243

```

244

245

## Usage Examples

246

247

### Basic Playback Control

248

249

```python

250

import spotipy

251

from spotipy.oauth2 import SpotifyOAuth

252

253

scope = "user-read-playback-state user-modify-playback-state"

254

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))

255

256

# Get current playback

257

current = sp.current_playback()

258

if current:

259

print(f"Currently playing: {current['item']['name']}")

260

print(f"Artist: {current['item']['artists'][0]['name']}")

261

print(f"Device: {current['device']['name']}")

262

print(f"Is playing: {current['is_playing']}")

263

print(f"Progress: {current['progress_ms']/1000:.1f}s / {current['item']['duration_ms']/1000:.1f}s")

264

265

# Pause if playing, resume if paused

266

if current['is_playing']:

267

sp.pause_playback()

268

print("Paused playback")

269

else:

270

sp.start_playback()

271

print("Resumed playback")

272

else:

273

print("No active playback")

274

```

275

276

### Device Management

277

278

```python

279

# Get available devices

280

devices_response = sp.devices()

281

devices = devices_response['devices']

282

283

print("Available devices:")

284

for device in devices:

285

status = "πŸ”Š ACTIVE" if device['is_active'] else "πŸ’€ Inactive"

286

print(f" {status} {device['name']} ({device['type']}) - Volume: {device['volume_percent']}%")

287

288

# Transfer to specific device

289

if devices:

290

# Find computer or smartphone

291

preferred_device = None

292

for device in devices:

293

if device['type'] in ['Computer', 'Smartphone'] and not device['is_restricted']:

294

preferred_device = device

295

break

296

297

if preferred_device:

298

print(f"\\nTransferring playback to: {preferred_device['name']}")

299

sp.transfer_playback(preferred_device['id'], force_play=True)

300

```

301

302

### Advanced Playback Control

303

304

```python

305

# Start playing a specific album

306

album_uri = "spotify:album:4aawyAB9vmqN3uQ7FjRGTy" # Example album

307

sp.start_playback(context_uri=album_uri)

308

print("Started playing album")

309

310

# Skip to track 3 in the album

311

sp.start_playback(

312

context_uri=album_uri,

313

offset={"position": 2} # 0-indexed, so position 2 is track 3

314

)

315

print("Started playing track 3 of album")

316

317

# Play specific tracks

318

track_uris = [

319

"spotify:track:4iV5W9uYEdYUVa79Axb7Rh", # Mr. Brightside

320

"spotify:track:0VjIjW4GlUAOLklx2J", # Bohemian Rhapsody

321

]

322

sp.start_playback(uris=track_uris)

323

print("Started playing specific tracks")

324

325

# Seek to 1 minute into current track

326

sp.seek_track(60000) # 60,000 milliseconds = 1 minute

327

print("Seeked to 1 minute")

328

```

329

330

### Queue Management

331

332

```python

333

# Get current queue

334

queue_info = sp.queue()

335

print(f"Currently playing: {queue_info['currently_playing']['name']}")

336

print("\\nUpcoming in queue:")

337

338

for i, track in enumerate(queue_info['queue'][:5], 1): # Show next 5 tracks

339

artist_names = ', '.join([artist['name'] for artist in track['artists']])

340

print(f" {i}. {track['name']} - {artist_names}")

341

342

# Add tracks to queue

343

tracks_to_add = [

344

"spotify:track:1301WleyT98MSxVHPZCA6M", # Sweet Child O' Mine

345

"spotify:track:4VqPOruhp5EdPBeR92t6lQ", # Stairway to Heaven

346

]

347

348

for track_uri in tracks_to_add:

349

sp.add_to_queue(track_uri)

350

print(f"Added track to queue: {track_uri}")

351

```

352

353

### Playback Settings Control

354

355

```python

356

# Get current playback to check settings

357

current = sp.current_playback()

358

if current:

359

print(f"Shuffle: {'On' if current['shuffle_state'] else 'Off'}")

360

print(f"Repeat: {current['repeat_state']}")

361

print(f"Volume: {current['device']['volume_percent']}%")

362

363

# Toggle shuffle

364

new_shuffle = not current['shuffle_state']

365

sp.shuffle(new_shuffle)

366

print(f"Set shuffle to: {'On' if new_shuffle else 'Off'}")

367

368

# Cycle through repeat modes

369

repeat_modes = ['off', 'context', 'track']

370

current_repeat = current['repeat_state']

371

next_repeat_index = (repeat_modes.index(current_repeat) + 1) % len(repeat_modes)

372

next_repeat = repeat_modes[next_repeat_index]

373

374

sp.repeat(next_repeat)

375

print(f"Set repeat to: {next_repeat}")

376

377

# Adjust volume

378

current_volume = current['device']['volume_percent']

379

new_volume = min(100, current_volume + 10) # Increase by 10%, max 100%

380

sp.volume(new_volume)

381

print(f"Set volume to: {new_volume}%")

382

```

383

384

### Playback Monitoring

385

386

```python

387

import time

388

389

def monitor_playback(duration_seconds=60):

390

"""Monitor playback for specified duration."""

391

print(f"Monitoring playback for {duration_seconds} seconds...")

392

393

last_track = None

394

start_time = time.time()

395

396

while time.time() - start_time < duration_seconds:

397

current = sp.current_playback()

398

399

if current and current['item']:

400

track_name = current['item']['name']

401

artist_name = current['item']['artists'][0]['name']

402

progress_ms = current['progress_ms']

403

duration_ms = current['item']['duration_ms']

404

is_playing = current['is_playing']

405

406

# Check if track changed

407

if track_name != last_track:

408

print(f"\\n🎡 Now playing: {track_name} - {artist_name}")

409

last_track = track_name

410

411

# Show progress

412

progress_percent = (progress_ms / duration_ms) * 100

413

status = "▢️ Playing" if is_playing else "⏸️ Paused"

414

print(f"\\r{status} [{progress_percent:5.1f}%] {progress_ms//1000:3d}s / {duration_ms//1000:3d}s", end="")

415

else:

416

print("\\rNo active playback", end="")

417

418

time.sleep(2) # Update every 2 seconds

419

420

print("\\nMonitoring finished")

421

422

# Run monitoring

423

monitor_playback(30) # Monitor for 30 seconds

424

```

425

426

### Smart Playlist Player

427

428

```python

429

def play_playlist_smartly(playlist_id, shuffle=True, start_from_position=None):

430

"""Play playlist with smart features."""

431

432

# Get playlist info

433

playlist = sp.playlist(playlist_id)

434

print(f"Playing playlist: {playlist['name']}")

435

print(f"Total tracks: {playlist['tracks']['total']}")

436

437

# Set shuffle if requested

438

if shuffle:

439

sp.shuffle(True)

440

print("Shuffle enabled")

441

442

# Start playback

443

if start_from_position:

444

sp.start_playback(

445

context_uri=playlist['uri'],

446

offset={"position": start_from_position}

447

)

448

print(f"Started from position {start_from_position + 1}")

449

else:

450

sp.start_playback(context_uri=playlist['uri'])

451

print("Started from beginning")

452

453

# Set moderate volume

454

sp.volume(70)

455

print("Set volume to 70%")

456

457

# Use the smart player

458

playlist_id = "37i9dQZF1DXcBWIGoYBM5M" # Example: Today's Top Hits

459

play_playlist_smartly(playlist_id, shuffle=True, start_from_position=5)

460

```

461

462

### Error Handling for Premium Features

463

464

```python

465

from spotipy.exceptions import SpotifyException

466

467

def safe_playback_control(action_func, *args, **kwargs):

468

"""Safely execute playback control with error handling."""

469

try:

470

action_func(*args, **kwargs)

471

return True

472

except SpotifyException as e:

473

if e.http_status == 403:

474

print("❌ Premium subscription required for playback control")

475

elif e.http_status == 404:

476

print("❌ No active device found")

477

else:

478

print(f"❌ Playback error: {e.msg}")

479

return False

480

481

# Examples with error handling

482

if safe_playback_control(sp.start_playback):

483

print("βœ… Playback started successfully")

484

485

if safe_playback_control(sp.next_track):

486

print("βœ… Skipped to next track")

487

488

if safe_playback_control(sp.volume, 80):

489

print("βœ… Volume set to 80%")

490

```

491

492

## Important Notes

493

494

### Premium Subscription Requirements

495

496

Most playback control features require a Spotify Premium subscription:

497

498

- **Premium Required**: `start_playback`, `pause_playback`, `next_track`, `previous_track`, `seek_track`, `shuffle`, `repeat`, `volume`, `transfer_playback`, `add_to_queue`

499

- **Free Tier**: `current_playback`, `currently_playing`, `devices`, `queue` (read-only)

500

501

### Device Availability

502

503

- Playback control requires an active Spotify device (desktop app, mobile app, web player, or Connect device)

504

- Use `devices()` to check for available devices before attempting playback control

505

- Transfer playback to ensure target device is active

506

507

### Rate Limiting

508

509

Playback endpoints have rate limits. Avoid rapid successive calls to prevent API errors.

510

511

## Required Scopes Summary

512

513

- **user-read-playback-state**: Read current playback state and queue

514

- **user-read-currently-playing**: Read currently playing content

515

- **user-modify-playback-state**: Control playback (requires Premium)