Beispiel #1
0
    def __init__(self):
        threading.Thread.__init__(self)

        self.nextFile = None
        self.needsStop = False
        self.needsAbort = False

        self.controlLock = threading.Lock()

        self._currentlyPlaying = False
        self.playLock = threading.Lock()

        self._shoutcaster = shout.Shout()
        print "Initializing new shoutcast interface, using libshout version %s" % shout.version(
        )

        self._shoutcaster.password = open(
            os.path.join(os.path.dirname(__file__), "password.txt"),
            "r").read()
        self._shoutcaster.mount = '/partybot'
        self._shoutcaster.format = 'mp3'

        self._shoutcaster.name = 'PartyBot Jukebox'

        self._inputStream = None
        self._silenceStream = None
Beispiel #2
0
    def __init__(self, host, port, password):
        self.shout = shout.Shout()
        logger.info("Creating new streamer (libshout version %s)...",
                    shout.version())

        # Set stream metadata
        self.shout.audio_info = {
            shout.SHOUT_AI_BITRATE: "128",
            shout.SHOUT_AI_SAMPLERATE: "44100",
            shout.SHOUT_AI_CHANNELS: "2"
        }
        self.shout.ogv = 0
        self.shout.format = "mp3"

        # Set connection information
        self.shout.host = host
        self.shout.port = int(port)
        self.shout.mount = "/stream"
        self.shout.user = "******"
        self.shout.password = password

        # Set stream information
        self.shout.name = "NitroDJ"
        self.shout.genre = "Various"
        self.shout.description = "NitroDJ instance"
        self.shout.url = "http://{}:{}/stream".format(host, port)

        self.shout.open()
        self.shout.close()
Beispiel #3
0
    def __init__(self):
        super(PlayerThread, self).__init__()
        self.logger = logging.getLogger(__name__)
        self.logger.info("Creating PlayerThread")
        self.play_q = Queue.Queue()
        self.is_playing = False
        self.connected = False
        self.pause_request = threading.Event()
        self.stop_request = threading.Event()
        # shutdown_request always implies stop_request
        # Always set stop_request when shutdown_request is set!
        self.shutdown_request = threading.Event()

        #self.silence_path = os.path.join(settings.MEDIA_ROOT, "silence_1s.mp3")
        self.silence_path = os.path.join(settings.MEDIA_ROOT,
                                         "small_silence.mp3")
        self.mp3_silence = open(self.silence_path).read()

        self.shout = shout.Shout()
        self.shout.host = settings.JUKEBOX_SHOUT_HOST
        self.shout.port = settings.JUKEBOX_SHOUT_PORT
        self.shout.user = settings.JUKEBOX_SHOUT_USER
        self.shout.password = settings.JUKEBOX_SHOUT_PASSWORD
        self.shout.mount = settings.JUKEBOX_SHOUT_MOUNT
        self.shout.name = settings.JUKEBOX_SHOUT_NAME
        self.shout.genre = settings.JUKEBOX_SHOUT_GENRE
        self.shout.url = settings.JUKEBOX_SHOUT_URL
        self.shout.public = settings.JUKEBOX_SHOUT_PUBLIC
        # self.shout.audio_info = { 'key': 'val', ... }
        #  (keys are shout.SHOUT_AI_BITRATE, shout.SHOUT_AI_SAMPLERATE,
        #   shout.SHOUT_AI_CHANNELS, shout.SHOUT_AI_QUALITY)
        self.shout.format = b"mp3"
Beispiel #4
0
def channel(threadname, loc):
    s = shout.Shout()
    # print "Using libshout version %s" % shout.version()

    global threadcount, activethreads

    # s.host = 'localhost'
    # s.port = 8000
    # s.user = '******'
    s.password = "******"
    s.mount = "/pyshout" + str(loc) + ".mp3"
    s.protocol = 'http'
    s.format = 'mp3'
    # s.format = 'vorbis' | 'mp3'
    # s.protocol = 'http' | 'xaudiocast' | 'icy'
    # s.name = ''
    # s.genre = ''
    # s.url = ''
    # s.public = 0 | 1
    # s.audio_info = { 'key': 'val', ... }
    #  (keys are shout.SHOUT_AI_BITRATE, shout.SHOUT_AI_SAMPLERATE,
    #   shout.SHOUT_AI_CHANNELS, shout.SHOUT_AI_QUALITY)

    s.open()

    total = 0
    st = time.time()

    fa = '1.mp3'

    # for fa in sys.argv[1:]:
    print "opening file %s" % fa
    f = open(fa, 'r')
    s.set_metadata({'song': fa})

    nbuf = f.read(4096)
    while 1:
        buf = nbuf
        nbuf = f.read(4096)
        total = total + len(buf)
        if len(buf) == 0:
            break
        s.send(buf)
        s.sync()
    f.close()

    et = time.time()
    br = total * 0.008 / (et - st)
    print "Sent %d bytes in %d seconds (%f kbps)" % (total, et - st, br)

    print s.close()
    thread.interrupt_main()
Beispiel #5
0
 def __init__(self,
              host="localhost",
              port=8501,
              user='******',
              password='******',
              mount='/mymout'):
     self._s = shout.Shout()
     self._s.host = host
     self._s.port = port
     self._s.user = user
     self._s.password = password
     self._s.mount = mount
     self._status = shout.SHOUTERR_UNCONNECTED
Beispiel #6
0
    def __init__(self):
        Thread.__init__(self)

        musicflag = 0  ### set to 1 for music or 0 for silence between speech

        beep_file = 'morse.aiff.mp3'

        self.silence = []

        if musicflag == 1:
            self.silence = []

            for silchunk in range(1, 11):
                silence_file = '%s.mp3' % silchunk
                #print "Read in %s.mp3" % silchunk

                f = open(silence_file, 'rb')
                self.silence.append(f.read())
                f.close()

        elif musicflag == 0:
            self.silence.append(open("silence.true.mp3", "rb").read())

        ##print self.silence

        f = open(beep_file, 'rb')
        self.beep = f.read()
        f.close()
        s = shout.Shout()
        s.host = 'irc.00id.net'
        s.port = 8000
        s.user = '******'
        s.password = '******'  #the source password as defined in your icecast.xml
        s.mount = "/stream"
        s.format = 'mp3'  #'vorbis' | 'mp3'
        # s.protocol = 'http' | 'xaudiocast' | 'icy'
        # s.name = ''
        # s.genre = ''
        # s.url = ''
        # s.public = 0 | 1
        s.audio_info = {'shout.SHOUT_AI_BITRATE': '48'}
        #  (keys are shout.SHOUT_AI_BITRATE, shout.SHOUT_AI_SAMPLERATE,
        #   shout.SHOUT_AI_CHANNELS, shout.SHOUT_AI_QUALITY)
        self.broadcast = s
        self.broadcast.open()
Beispiel #7
0
 def __init__ (self, channel_mount, music_directory, station_url, genre,name,         description, bitrate="128", samplerate="44100", channels="5",music_format="mp3", ogv=0):
  #connection to icecast
  global hostname,port,password
  self.song_conter= 0
  self.s = shout.Shout()
  self.s.audio_info = {shout.SHOUT_AI_BITRATE:bitrate,   shout.SHOUT_AI_SAMPLERATE:samplerate, shout.SHOUT_AI_CHANNELS:channels}
  self.s.name = name
  self.s.url = station_url
  self.s.mount = channel_mount
  self.s.port = port
  self.ogv = ogv
  self.s.password = password
  self.s.genre = genre
  self.music_directory = music_directory
  self.s.description = description
  self.s.host = hostname
  self.s.format = music_format #using mp3 but it can also be ogg vorbis
  print self.s.open()
  threading.Thread.__init__ (self)
Beispiel #8
0
def stream_music(song):
  s = shout.Shout()
  s.password = "******"
  s.mount = "/pyshout/" + song
  s.protocol = 'http'
  s.format = 'mp3'

  try:
    s.open()
  except:
    wait = 1 + (3 * random.random())
    time.sleep(wait)
    s.open()

  total = 0
  st = time.time()

  while True:
    print "opening file %s" % song
    f = open(song, 'r')
    s.set_metadata({'song': song})

    nbuf = f.read(4096)
    while 1:
      buf = nbuf
      nbuf = f.read(4096)
      total = total + len(buf)
      if len(buf) == 0:
        break
      s.send(buf)
      s.sync()
    f.close()

    et = time.time()
    br = total*0.008/(et-st)
    print "Sent %d bytes in %d seconds (%f kbps)" % (total, et-st, br)

  s.close()
  return song
Beispiel #9
0
    def __init__(
        self,
        host: str,
        port: int,
        password: str,
        name: str,
        id: str,
        genre: str,
        description: str,
        format: str = "mp3",
        user: str = "source",
    ) -> None:
        self.conn = shout.Shout()

        self.conn.host = host
        self.conn.port = port
        self.conn.password = password
        self.conn.name = name
        self.conn.mount = f"/{id}"
        self.conn.genre = genre
        self.conn.description = description
        self.conn.format = format
        self.conn.user = user
Beispiel #10
0
        except yaml.scanner.ScannerError, e:
            sys.exit("Error in configuration file: %s" % e)

    m = MPDClient()
    m.timeout = 60
    m.idletimeout = None

    # connect to the local running instance
    m.connect("localhost", 6600)

    conn = setupDB(cfg["database"]["hostname"], cfg["database"]["username"],
                   cfg["database"]["password"], cfg["database"]["database"])

    cursor = conn.cursor(buffered=True)

    s = shout.Shout()
    s.port = cfg["stream"]["port"]
    s.host = cfg["stream"]["hostname"]
    s.mount = cfg["stream"]["mount"]
    s.password = cfg["stream"]["password"]

    try:
        s.open()
    # we can just ignore this - for some strange reason
    except shout.ShoutException:
        pass

    db = PlaylistDB(conn, cursor)

    # everything is set up, get ready to receive new events
    while 1:
Beispiel #11
0
    def __init__(self, station, q, logqueue, m3u):
        Thread.__init__(self)
        self.station = station
        self.q = q
        self.logqueue = logqueue
        self.m3u = m3u

        self.current_media_obj = MediaBase()

        if 'station_statusfile' in self.station:
            self.statusfile = station['station_statusfile']
            try:
                if os.path.exists(self.statusfile):
                    f = open(self.statusfile, 'r')
                    self.starting_id = int(f.read())
                    f.close()
            except:
                pass

        if 'base_dir' in self.station:
            self.base_directory = self.station['base_dir'].strip()

        # Media
        if 'm3u' in self.station['media']:
            if not self.station['media']['m3u'].strip() == '':
                self.media_source = self._path_add_base(self.station['media']['m3u'])

        if 'dir' in self.station['media']:
            if not self.station['media']['dir'].strip() == '':
                self.media_source = self._path_add_base(self.station['media']['dir'])

        if 'source' in self.station['media']:
            if not self.station['media']['source'].strip() == '':
                self.media_source = self._path_add_base(self.station['media']['source'])

        assert os.path.exists(self.media_source), 'The source directory or file does not exist.'

        # MySQL
        if 'mysql' in self.station['media']:
            if 'host' in self.station['media']['mysql']:
                self.mdb_host = self.station['media']['mysql']['host']
            if 'port' in self.station['media']['mysql']:
                self.mdb_port = self.station['media']['mysql']['port']
            if 'user' in self.station['media']['mysql']:
                self.mdb_user = self.station['media']['mysql']['user']
            if 'password' in self.station['media']['mysql']:
                self.mdb_password = self.station['media']['mysql']['password']
            if 'database' in self.station['media']['mysql']:
                self.mdb_database = self.station['media']['mysql']['database']
            if 'table' in self.station['media']['mysql']:
                self.mdb_table = self.station['media']['mysql']['table']
            if 'field' in self.station['media']['mysql']:
                self.mdb_field = self.station['media']['mysql']['field']

        self.media_format = self.station['media']['format']
        self.shuffle_mode = int(self.station['media']['shuffle'])
        self.bitrate = int(self.station['media']['bitrate'])
        self.ogg_quality = int(self.station['media']['ogg_quality'])
        self.samplerate = int(self.station['media']['samplerate'])
        self.voices = int(self.station['media']['voices'])

        # Server
        if 'mountpoint' in self.station['server']:
            self.mountpoint = self.station['server']['mountpoint']
        elif 'short_name' in self.station['infos']:
            self.mountpoint = self.station['infos']['short_name']
        else:
            self.mountpoint = 'default'

        self.short_name = self.mountpoint

        if 'appendtype' in self.station['server']:
            self.appendtype = int(self.station['server']['appendtype'])

        if 'type' in self.station['server']:
            self.type = self.station['server']['type']  # 'icecast' | 'stream-m'
        else:
            self.type = 'icecast'

        if 'stream-m' in self.type:
            self.channel = HTTPStreamer()
            self.channel.mount = '/publish/' + str(self.mountpoint)
        elif 'icecast' in self.type:
            self.channel = shout.Shout()
            self.channel.mount = '/' + str(self.mountpoint)
            if self.appendtype:
                self.channel.mount = str(self.channel.mount) + '.' + str(self.media_format)
        else:
            self._err('Not a compatible server type. Choose "stream-m" or "icecast".')
            return

        # Shout requires non-unicode strings
        self.channel.url = str(self.station['infos']['url'])
        self.channel.name = str(self.station['infos']['name'])
        self.channel.genre = str(self.station['infos']['genre'])
        self.channel.description = str(self.station['infos']['description'])
        self.channel.format = str(self.media_format)
        self.channel.host = str(self.station['server']['host'])
        self.channel.port = int(self.station['server']['port'])
        self.channel.user = '******'
        self.channel.password = str(self.station['server']['sourcepassword'])
        self.channel.public = int(self.station['server']['public'])
        if self.channel.format == 'mp3':
            self.channel.audio_info = {'bitrate': str(self.bitrate),
                                       'samplerate': str(self.samplerate),
                                       'channels': str(self.voices), }
        else:
            self.channel.audio_info = {'bitrate': str(self.bitrate),
                                       'samplerate': str(self.samplerate),
                                       'quality': str(self.ogg_quality),
                                       'channels': str(self.voices), }

        self.server_url = 'http://' + str(self.channel.host) + ':' + str(self.channel.port)
        self.channel_url = self.server_url + self.channel.mount

        # RSS
        if 'feeds' in self.station:
            self.station['rss'] = self.station['feeds']

        if 'rss' in self.station:

            if 'mode' in self.station['rss']:
                self.feeds_mode = int(self.station['rss']['mode'])
                if self.feeds_mode:
                    self.feeds_dir = self._path_add_base(self.station['rss']['dir'])
                    self.feeds_enclosure = int(self.station['rss']['enclosure'])
            if 'json' in self.station['rss']:
                self.feeds_json = int(self.station['rss']['json'])
            if 'rss' in self.station['rss']:
                self.feeds_rss = int(self.station['rss']['rss'])
            if 'playlist' in self.station['rss']:
                self.feeds_playlist = int(self.station['rss']['playlist'])
            if 'showfilename' in self.station['rss']:
                self.feeds_showfilename = int(self.station['rss']['showfilename'])
            if 'showfilepath' in self.station['rss']:
                self.feeds_showfilepath = int(self.station['rss']['showfilepath'])

            self.feeds_media_url = self.channel.url + '/media/'
            if 'media_url' in self.station['rss']:
                if not self.station['rss']['media_url'] == '':
                    self.feeds_media_url = self.station['rss']['media_url']

        if self.feeds_dir:
            self.base_name = self.feeds_dir + os.sep + self.short_name + '_' + self.channel.format
        else:
             self.base_name = self.short_name + '_' + self.channel.format

        self.feeds_current_file = self.base_name + '_current'
        self.feeds_playlist_file = self.base_name + '_playlist'

        # Logging
        self._info('Opening ' + self.short_name + ' - ' + self.channel.name)

        self.metadata_relative_dir = 'metadata'
        self.metadata_url = self.channel.url + '/rss/' + self.metadata_relative_dir
        self.metadata_dir = self.feeds_dir + os.sep + self.metadata_relative_dir

        if self.feeds_mode and not os.path.exists(self.metadata_dir):
            os.makedirs(self.metadata_dir)

        # The station's player
        self.player = Player(self.type)

        # OSCing
        # mode = 0 means Off, mode = 1 means On
        if 'control' in self.station:
            self.osc_control_mode = int(self.station['control']['mode'])
            if self.osc_control_mode:
                self.osc_port = int(self.station['control']['port'])
                self.osc_controller = OSCController(self.osc_port)
                # OSC paths and callbacks
                self.osc_controller.add_method('/media/next', 'i', self.media_next_callback)
                self.osc_controller.add_method('/media/relay', 'i', self.relay_callback)
                self.osc_controller.add_method('/twitter', 'i', self.twitter_callback)
                self.osc_controller.add_method('/jingles', 'i', self.jingles_callback)
                self.osc_controller.add_method('/record', 'i', self.record_callback)
                self.osc_controller.add_method('/player', 'i', self.player_callback)
                self.osc_controller.add_method('/run', 'i', self.run_callback)
                self.osc_controller.start()

        # Jingling between each media.
        if 'jingles' in self.station:
            if 'mode' in self.station['jingles']:
                self.jingles_mode = int(self.station['jingles']['mode'])
            if 'shuffle' in self.station['jingles']:
                self.jingles_shuffle = int(self.station['jingles']['shuffle'])
            if 'frequency' in self.station['jingles']:
                self.jingles_frequency = int(self.station['jingles']['frequency'])
            if 'dir' in self.station['jingles']:
                self.jingles_dir = self._path_add_base(self.station['jingles']['dir'])
            if self.jingles_mode == 1:
                self.jingles_callback('/jingles', [1])

        # Relaying
        if 'relay' in self.station:
            self.relay_mode = int(self.station['relay']['mode'])
            self.relay_url = self.station['relay']['url']
            self.relay_author = self.station['relay']['author']
            if self.relay_mode == 1:
                self.relay_callback('/media/relay', [1])

        # Twitting
        if 'twitter' in self.station:
            self.twitter_mode = int(self.station['twitter']['mode'])
            self.twitter_key = self.station['twitter']['key']
            self.twitter_secret = self.station['twitter']['secret']
            self.twitter_tags = self.station['twitter']['tags'].split(' ')
            try:
                self.twitter_messages = self.station['twitter']['message']
                if isinstance(self.twitter_messages, dict):
                    self.twitter_messages = list(self.twitter_messages)
            except:
                pass

            if self.twitter_mode:
                self.twitter_callback('/twitter', [1])

        # Recording
        if 'record' in self.station:
            self.record_mode = int(self.station['record']['mode'])
            self.record_dir = self._path_add_base(self.station['record']['dir'])
            if self.record_mode:
                self.record_callback('/record', [1])

        self.valid = True
Beispiel #12
0
    def handle(self, *args, **options):
        pidFile = os.path.dirname(
            os.path.abspath(__file__)) + "/../../daemon.pid"

        if options["start"] or options["fg"]:
            if (options["host"] is None or options["port"] is None
                    or options["password"] is None):
                print "Required arguments: host, port, password"
                self.print_help("jukebox_shout", "help")
                return

            if os.path.exists(pidFile):
                print "Daemon already running, pid file exists"
                return

            pid = daemon.pidfile.TimeoutPIDLockFile(pidFile, 10)

            self.shout = shout.Shout()
            print "Using libshout version %s" % shout.version()

            self.shout.audio_info = {
                shout.SHOUT_AI_BITRATE: "128",
                shout.SHOUT_AI_SAMPLERATE: "44100",
                shout.SHOUT_AI_CHANNELS: "2"
            }
            self.shout.name = "Democratic Jukebox"
            self.shout.url = "http://" + options["host"] + ":" + \
                 options["port"] + "/stream"
            self.shout.mount = "/stream"
            self.shout.port = int(options["port"])
            self.shout.user = "******"
            self.shout.password = options["password"]
            self.shout.genre = "Mixed"
            self.shout.description = "Your democratic music player"
            self.shout.host = options["host"]
            self.shout.ogv = 0
            self.shout.format = "mp3"
            try:
                self.shout.open()
                self.shout.close()
            except shout.ShoutException as exception:
                print "Error: " + str(exception)
                return

            if options["start"]:
                print "Starting jukebox_shout daemon..."
                self.daemon = daemon.DaemonContext(
                    uid=os.getuid(),
                    gid=os.getgid(),
                    pidfile=pid,
                    working_directory=os.getcwd(),
                    detach_process=True,
                    signal_map={
                        SIGTSTP: self.shutdown,
                        SIGABRT: self.skipSong
                    })

                with self.daemon:
                    self.shout.open()

                    print "Register player"
                    pid = int(open(pidFile).read())
                    players_api = api.players()
                    players_api.add(pid)

                    songs_api = api.songs()
                    while 1:
                        self.sendfile(songs_api.getNextSong())

            elif options["fg"]:
                self.shout.open()

                print "Register player"
                pid = os.getpid()
                players_api = api.players()
                players_api.add(pid)

                songs_api = api.songs()
                while 1:
                    song = songs_api.getNextSong()
                    self.sendfile(song)

        elif options["stop"]:
            if not os.path.exists(pidFile):
                print "Daemon not running"
                return

            print "Stopping daemon..."
            pid = int(open(pidFile).read())
            os.kill(pid, SIGTSTP)

            print "Unregister player " + str(pid)
            players_api = api.players()
            players_api.remove(pid)
        else:
            self.print_help("jukebox_shout", "help")