0
# Client Control & Playback
1
2
Control Plex client applications, manage playback, navigate interfaces, and handle media streaming to various devices including specialized Sonos support.
3
4
## Capabilities
5
6
### PlexClient Connection
7
8
Interface for controlling Plex client applications and media playback.
9
10
```python { .api }
11
class PlexClient:
12
def __init__(self, server=None, data=None, initpath=None, baseurl=None, identifier=None, token=None, connect=True, session=None, timeout=None, parent=None):
13
"""
14
Create PlexClient for controlling a Plex player.
15
16
Args:
17
server (PlexServer, optional): Associated server
18
data (dict, optional): Client data from server
19
initpath (str, optional): Path used to generate data
20
baseurl (str, optional): Direct client URL
21
identifier (str, optional): Resource/machine identifier for specific client
22
token (str, optional): Authentication token
23
connect (bool): Whether to connect immediately
24
session (requests.Session, optional): HTTP session
25
timeout (int, optional): Request timeout
26
parent (optional): Parent object
27
"""
28
29
def connect(self, timeout=None):
30
"""
31
Establish connection to client.
32
33
Args:
34
timeout (int, optional): Connection timeout
35
36
Returns:
37
PlexClient: Connected client instance
38
39
Raises:
40
Unsupported: If client doesn't support remote control
41
"""
42
43
def proxyThroughServer(self, value=True, server=None):
44
"""
45
Route client commands through Plex server.
46
47
Args:
48
value (bool): Enable/disable server proxy
49
server (PlexServer, optional): Server to proxy through
50
"""
51
```
52
53
### Navigation Commands
54
55
Control client interface navigation and menu interaction.
56
57
```python { .api }
58
class PlexClient:
59
def goBack(self):
60
"""Navigate back to previous screen."""
61
62
def goToHome(self):
63
"""Navigate to home screen."""
64
65
def goToMusic(self):
66
"""Navigate to music section."""
67
68
def moveUp(self):
69
"""Move selection up."""
70
71
def moveDown(self):
72
"""Move selection down."""
73
74
def moveLeft(self):
75
"""Move selection left."""
76
77
def moveRight(self):
78
"""Move selection right."""
79
80
def select(self):
81
"""Select current item."""
82
83
def contextMenu(self):
84
"""Open context menu for current item."""
85
86
def pageUp(self):
87
"""Page up in current view."""
88
89
def pageDown(self):
90
"""Page down in current view."""
91
```
92
93
### Basic Playback Control
94
95
Fundamental playback control commands.
96
97
```python { .api }
98
class PlexClient:
99
def play(self, mtype='music'):
100
"""
101
Start or resume playback.
102
103
Args:
104
mtype (str): Media type ('music', 'video', 'photo')
105
"""
106
107
def pause(self, mtype='music'):
108
"""
109
Pause playback.
110
111
Args:
112
mtype (str): Media type ('music', 'video', 'photo')
113
"""
114
115
def stop(self, mtype='music'):
116
"""
117
Stop playback.
118
119
Args:
120
mtype (str): Media type ('music', 'video', 'photo')
121
"""
122
123
def skipNext(self):
124
"""Skip to next item in queue."""
125
126
def skipPrevious(self):
127
"""Skip to previous item in queue."""
128
129
def seekTo(self, offset, mtype='music'):
130
"""
131
Seek to specific time position.
132
133
Args:
134
offset (int): Time offset in milliseconds
135
mtype (str): Media type ('music', 'video', 'photo')
136
"""
137
```
138
139
### Volume & Playback Mode Control
140
141
Control audio volume and playback modes.
142
143
```python { .api }
144
class PlexClient:
145
def setVolume(self, volume, mtype='music'):
146
"""
147
Set playback volume.
148
149
Args:
150
volume (int): Volume level (0-100)
151
mtype (str): Media type ('music', 'video', 'photo')
152
"""
153
154
def setRepeat(self, repeat, mtype='music'):
155
"""
156
Set repeat mode.
157
158
Args:
159
repeat (int): Repeat mode (0=off, 1=repeat-one, 2=repeat-all)
160
mtype (str): Media type ('music', 'video', 'photo')
161
"""
162
163
def setShuffle(self, shuffle, mtype='music'):
164
"""
165
Set shuffle mode.
166
167
Args:
168
shuffle (bool): Enable/disable shuffle mode
169
mtype (str): Media type ('music', 'video', 'photo')
170
"""
171
```
172
173
### Media Playback
174
175
Control playback of specific media items.
176
177
```python { .api }
178
class PlexClient:
179
def playMedia(self, media, offset=0, **params):
180
"""
181
Play specific media item.
182
183
Args:
184
media: Media object to play (Movie, Episode, Track, etc.)
185
offset (int): Start offset in milliseconds
186
**params: Additional playback parameters
187
- shuffle (bool): Enable shuffle mode
188
- repeat (int): Repeat mode
189
- includeChapters (bool): Include chapter information
190
- includeRelated (bool): Include related content
191
"""
192
193
def setAudioStream(self):
194
"""Select audio stream for current media."""
195
196
def setSubtitleStream(self):
197
"""Select subtitle stream for current media."""
198
199
def setVideoStream(self):
200
"""Select video quality stream for current media."""
201
```
202
203
### Playback Status & Timeline
204
205
Monitor playback status and timeline information.
206
207
```python { .api }
208
class PlexClient:
209
def timelines(self, wait=0):
210
"""
211
Get playback timeline status.
212
213
Args:
214
wait (int): Wait time for timeline updates
215
216
Returns:
217
list: List of ClientTimeline objects for each media type
218
"""
219
220
def isPlayingMedia(self, includePaused=True):
221
"""
222
Check if client is playing media.
223
224
Args:
225
includePaused (bool): Include paused media as "playing"
226
227
Returns:
228
bool: True if media is playing/paused
229
"""
230
231
class ClientTimeline:
232
"""Playback timeline and status information."""
233
234
@property
235
def state(self):
236
"""str: Playback state ('playing', 'paused', 'stopped')."""
237
238
@property
239
def time(self):
240
"""int: Current playback time in milliseconds."""
241
242
@property
243
def duration(self):
244
"""int: Total media duration in milliseconds."""
245
246
@property
247
def ratingKey(self):
248
"""str: Currently playing media rating key."""
249
250
@property
251
def type(self):
252
"""str: Media type ('video', 'music', 'photo')."""
253
```
254
255
### Specialized Sonos Support
256
257
Control Sonos speakers through Plex integration.
258
259
```python { .api }
260
class PlexSonosClient:
261
"""Specialized client for controlling Sonos speakers."""
262
263
def __init__(self, server, data, initpath=None):
264
"""
265
Create Sonos client controller.
266
267
Args:
268
server (PlexServer): Associated Plex server
269
data (dict): Sonos device data
270
initpath (str, optional): Initialization path
271
"""
272
273
def playMedia(self, media, **kwargs):
274
"""Play media on Sonos speaker."""
275
276
def setVolume(self, volume):
277
"""Set Sonos speaker volume."""
278
279
def play(self):
280
"""Start/resume Sonos playback."""
281
282
def pause(self):
283
"""Pause Sonos playback."""
284
285
def stop(self):
286
"""Stop Sonos playback."""
287
```
288
289
## Usage Examples
290
291
### Basic Client Control
292
293
```python
294
from plexapi.server import PlexServer
295
296
plex = PlexServer('http://localhost:32400', token='your-token')
297
298
# Get available clients
299
clients = plex.clients()
300
for client in clients:
301
print(f"Client: {client.title} ({client.product})")
302
303
# Connect to specific client
304
tv_client = plex.client('Living Room TV')
305
tv_client.connect()
306
307
# Basic playback control
308
tv_client.play()
309
tv_client.pause()
310
tv_client.stop()
311
```
312
313
### Media Playback
314
315
```python
316
# Get media to play
317
movie = plex.library.section('Movies').get('The Matrix')
318
episode = plex.library.section('TV Shows').get('The Office').episode(season=1, episode=1)
319
320
# Play media on client
321
tv_client.playMedia(movie)
322
tv_client.playMedia(episode, offset=30000) # Start 30 seconds in
323
324
# Control playback
325
tv_client.seekTo(120000) # Seek to 2 minutes
326
tv_client.skipNext() # Skip to next item
327
```
328
329
### Navigation Control
330
331
```python
332
# Navigate client interface
333
tv_client.goToHome()
334
tv_client.goToMusic()
335
336
# Menu navigation
337
tv_client.moveDown()
338
tv_client.moveRight()
339
tv_client.select()
340
tv_client.contextMenu()
341
342
# Page navigation
343
tv_client.pageDown()
344
tv_client.goBack()
345
```
346
347
### Volume and Playback Modes
348
349
```python
350
# Volume control
351
tv_client.setVolume(75) # Set volume to 75%
352
353
# Playback modes
354
tv_client.setRepeat(1) # Repeat current item
355
tv_client.setShuffle(True) # Enable shuffle
356
357
# Stream selection for video
358
tv_client.setAudioStream() # Cycle audio streams
359
tv_client.setSubtitleStream() # Cycle subtitle streams
360
```
361
362
### Monitoring Playback Status
363
364
```python
365
# Check if playing
366
if tv_client.isPlayingMedia():
367
print("Client is currently playing media")
368
369
# Get detailed timeline information
370
timelines = tv_client.timelines()
371
for timeline in timelines:
372
if timeline.state == 'playing':
373
progress = (timeline.time / timeline.duration) * 100
374
print(f"Playing: {timeline.type} - {progress:.1f}% complete")
375
print(f"Time: {timeline.time // 1000}s / {timeline.duration // 1000}s")
376
```
377
378
### Advanced Client Features
379
380
```python
381
# Proxy through server for remote clients
382
tv_client.proxyThroughServer(True, server=plex)
383
384
# Play with advanced options
385
tv_client.playMedia(
386
movie,
387
offset=0,
388
shuffle=False,
389
repeat=0,
390
includeChapters=True,
391
includeRelated=True
392
)
393
394
# Timeline monitoring with updates
395
import time
396
while tv_client.isPlayingMedia():
397
timelines = tv_client.timelines(wait=1000) # Wait 1 second for updates
398
for timeline in timelines:
399
if timeline.state == 'playing':
400
print(f"Current time: {timeline.time // 1000}s")
401
time.sleep(1)
402
```
403
404
### Sonos Integration
405
406
```python
407
# Find Sonos devices
408
sonos_clients = [c for c in plex.clients() if 'sonos' in c.product.lower()]
409
410
if sonos_clients:
411
sonos = sonos_clients[0]
412
413
# Play music on Sonos
414
album = plex.library.section('Music').get('Abbey Road')
415
sonos.playMedia(album)
416
417
# Control Sonos playback
418
sonos.setVolume(50)
419
sonos.pause()
420
sonos.play()
421
```
422
423
### Error Handling
424
425
```python
426
from plexapi.exceptions import Unsupported, NotFound
427
428
try:
429
# Try to connect to client
430
client = plex.client('Bedroom TV')
431
client.connect()
432
433
# Try to play media
434
movie = plex.library.section('Movies').get('Some Movie')
435
client.playMedia(movie)
436
437
except NotFound as e:
438
print(f"Client or media not found: {e}")
439
440
except Unsupported as e:
441
print(f"Client doesn't support remote control: {e}")
442
```
443
444
### Multi-Client Control
445
446
```python
447
# Control multiple clients simultaneously
448
clients = plex.clients()
449
connected_clients = []
450
451
# Connect to all available clients
452
for client in clients:
453
try:
454
client.connect()
455
connected_clients.append(client)
456
print(f"Connected to {client.title}")
457
except Unsupported:
458
print(f"{client.title} doesn't support remote control")
459
460
# Pause all clients
461
for client in connected_clients:
462
if client.isPlayingMedia():
463
client.pause()
464
print(f"Paused {client.title}")
465
466
# Resume all clients
467
for client in connected_clients:
468
client.play()
469
print(f"Resumed {client.title}")
470
```