home-assistant-libs / pychromecast

Library for Python 3 to communicate with the Google Chromecast.
MIT License
2.52k stars 378 forks source link

Stop a running stream #150

Open ttopholm opened 7 years ago

ttopholm commented 7 years ago

Hi All,

I have made a small Flask API to start a stream, which works fine:

# -*- coding: utf-8 -*-

import pychromecast
import time
from flask import Flask, request
app = Flask(__name__)

class Cast(object):

    def __init__(self, ip):
        self.cast = pychromecast.Chromecast(ip)
        self.mc = self.cast.media_controller

    def start(self, url, title, thumbnail):
        self.cast.play_media(url, 'application/vnd.ms-sstr+xml', title=title, thumb=thumbnail)

    def stop(self):
        mc = self.cast.media_controller
        mc.stop()

    def play(self):
        self.mc.play()

    def pause(self):
        self.mc.pause()

@app.route("/start", methods=["POST"])
def start():
    ip = request.form["ip"]
    url = request.form["url"]
    title = request.form["title"]
    thumbnail = request.form["thumbnail"]
    c = Cast(ip)
    c.start(url, title, thumbnail)
    return "OK"

@app.route("/stop", methods=["POST"])
def stop():
    ip = request.form["ip"]
    c = Cast(ip)
    c.stop()
    return "OK"

@app.route("/pause", methods=["POST"])
def pause():
    ip = request.form["ip"]
    c = Cast(ip)
    c.pause()
    return "OK"

@app.route("/play", methods=["POST"])
def play():
    ip = request.form["ip"]
    c = Cast(ip)
    c.play()
    return "OK"

if __name__ == "__main__":
    app.run(port=5555, host="0.0.0.0")

But if I call /stop or any order command they don't work. If I make a python script and just run it from the command line in one go it works fine:

# -*- coding: utf-8 -*-

import pychromecast
import time

class Cast(object):

    def __init__(self, ip):
        self.cast = pychromecast.Chromecast(ip)
        self.mc = self.cast.media_controller

    def start(self, url, title, thumbnail):
        self.cast.play_media(url, 'application/vnd.ms-sstr+xml', title=title, thumb=thumbnail)

    def stop(self):
        self.mc.stop()

    def play(self):
        self.mc.play()

    def pause(self):
        self.mc.pause()

if __name__ == "__main__":
    cast = Cast("1.2.3.4")
    cast.start("url", "demo", "http://demo")
    time.sleep(10)
    cast.stop()

Is there a way to keep the session?

emlove commented 7 years ago

Use triple ticks to escape a code sequence. For example:

```python code here ```

Also, See #128 and #145

ttopholm commented 7 years ago

Perfect, thanks....