Dave
Dave

Reputation: 261

mpv how to handle url errors

I trying to use the python-mpv module to stream audio, e.g. radio player, but don't know how I can handle failed URLs. My code using an incorrect URL is as follows:

import mpv

URL = 'http://51.89.148.171xxx:8022/stream'

player = mpv.MPV()
try:
    player.play(URL)
    player.wait_for_playback()
except Exception as ex:
    print(ex)

Upvotes: 1

Views: 193

Answers (1)

Ghorban M. Tavakoly
Ghorban M. Tavakoly

Reputation: 1249

I played a few minutes with python-mpv. Here are my findings, but it may be not best solution to your question.

First I added a log_handler to MPV instance:

import mpv


def log_handler(loglevel, component, message):
    print(f'loglevel={loglevel}, component={component}, message={message}')


player = mpv.MPV(log_handler=log_handler)
player.play('https://non-existent.domain/example-non-existent-stream')
player.wait_for_playback()
del player

After watching log output, I changed log_handler to capture url errors:

import mpv


def log_handler(loglevel, component, message):
    if loglevel == 'error' and component == 'stream':
        print(message)


player = mpv.MPV(log_handler=log_handler)
player.play('https://non-existent.domain/example-non-existent-stream')
player.wait_for_playback()
del player

Then I turned that to an exception:

import mpv


class UrlError(Exception):
    pass


def log_handler(loglevel, component, message):
    if loglevel == 'error' and component == 'stream':
        raise UrlError(message)


player = mpv.MPV(log_handler=log_handler)
try:
    player.play('https://non-existent.domain/example-non-existent-stream')
    player.wait_for_playback()
except UrlError as e:
    print(f'Hurray, here is the error: {e}')
finally:
    del player

Upvotes: 3

Related Questions