Пример #1
0
    def run(self):
        """
		Start the main loop.
		"""
        self.select_next_pending()
        delta_t = self.next_pending.time_pending() - get_date()
        sec_to_next = delta_t.total_seconds()
        sleep_time = sec_to_next - self.pre_wake_time

        if sec_to_next >= self.pre_wake_time:
            logger.info("Sleeping for %d seconds..." % sleep_time)
            time.sleep(sec_to_next - self.pre_wake_time)

        logger.info("alarm going of in %d seconds... preparing..." %
                    self.pre_wake_time)

        # prepare the alarm and shit
        self.next_pending.prepare()
        logger.debug("waiting...")
        while self.next_pending.time_pending() > get_date():
            time.sleep(1)

        logger.info("pling pling pling")
        self.next_pending.set_off()

        logger.info("starting over..")
        self.run()
Пример #2
0
    def debug(self):
        """
		Woo debugging
		"""
        logger.debug("alarm went off because of debuggingggg")
        self.select_next_pending()
        self.next_pending.prepare()
        self.next_pending.set_off()
Пример #3
0
    def load(self, q_list):
        """
		Takes a given list of queries in a string format
		and converts them into wav files which can be played later.
		"""
        logger.debug("loaded query handler")

        self.sound_list = self._queue_queries(q_list)
        self.loaded = True
Пример #4
0
    def play(self, delay=0):
        """
		Plays a prepared list of queries.
		"""
        logger.info("playing query list...")

        if not self.loaded:
            logger.warning("the query handler must be loaded to continue")
            return

        self._play_queries(delay, self.sound_list)

        logger.debug("played queries successfully...")
Пример #5
0
    def _run(self):
        """
		Private function that plays the loaded uncompressed file.
		"""
        while self._data != '' and self.playing:
            self._player.write(self._data)
            self._data = self._w.readframes(self._periodsize)

        self.playing = False

        time.sleep(self._end_delay)

        logger.debug("player thread stopped")
Пример #6
0
    def __init__(self, path=None):
        """
		Initialize a player object, either with or without a path.

		If it is not initalized with a path you have to use the load function
		to manually load object with a file. 
		"""
        logger.debug("initalizing player with sound: %s" % path)

        # with concurrent streams you will experience
        # stuttering if the periodsize is too big
        self._periodsize = 1024  # 8192

        if path != None:
            self.load(path)
Пример #7
0
    def _get_query(self, save_name, text):
        """
		Takes a given string and converts it into a .mp3 file,
		which can later be converted.
		"""
        try:
            li = text.split(" ")
            q = []
            maxlen = 100
            index = 0

            with open(save_name, "wb") as f:
                for i, w in enumerate(li):
                    neww = w + " "
                    newlist = list(q)
                    newlist.append(neww)
                    newlen = len(" ".join(newlist))

                    if newlen >= maxlen:
                        s = " ".join(q)
                        logger.debug("query string: %s" % s)

                        r = self._request_query(s, index)
                        f.write(r)

                        index += 1
                        q = []
                        q.append(w)
                    else:
                        q.append(neww)

                s = " ".join(q)
                logger.debug("query string: %s" % s)

                r = self._request_query(s, index)
                f.write(r)

            logger.info("successfully retrieved query translation...")
            return True

        except IOError as e:
            err = str(e)
            logger.error("ioerror saving query: %s" % err)

            return False
Пример #8
0
    def play(self, end_delay=0, join=True):
        """
		Play a loaded file.

		'end_delay' is the number of seconds to wait before actually finishing playing.
		
		If 'join' is true the main thread will wait for this one to
		finish before moving along.
		"""
        logger.debug("starting player thread")

        self.playing = True
        self._end_delay = end_delay
        self._data = self._w.readframes(self._periodsize)

        self._t.start()

        if join:
            self._t.join()
Пример #9
0
def convert_mp3(filename, overwrite=False):
	"""
	Convert a .mp3 file into a .mp3 file using pydub

	Overwrite True will convert the file even if the file exists
	"""
	in_path = abspath(filename)
	out_path = abspath(splitext(filename)[0]) + ".wav"

	logger.debug("converting file .mp3 to .wav:")
	logger.debug(" <- %s" % in_path)
	logger.debug(" -> %s" % out_path)

	if not isfile(out_path) or overwrite:
		AudioSegment.from_file(in_path).export(out_path, format="wav")
		logger.debug("conversion completed successfully...")
	else:
		logger.debug("file already exist.. skipping conversion..")

	return out_path
Пример #10
0
    def _queue_queries(self, queries):
        """
		Retrieves and converts a list of queries 
		and returns a list of the paths to the converted .wav files.
		"""
        sounds = []

        for i, q in enumerate(queries):
            template = "query/query-%d.%s"
            name = template % (i, "mp3")
            ret = self._get_query(name, q)

            if ret:
                wav = convert_mp3(name, True)
                sounds.append(wav)

                logger.info("queued up sound: %s" % wav)
                logger.debug(wav)
            else:
                logger.warning("failed to retreieve query: %s" % wav)

        return sounds
Пример #11
0
    def load(self, path):
        """
		Loads a uncompressed music file into the object.

		This can be called as many times as you would like
		during the lifetime of the object, as long as the previous
		file has finished playing.
		"""
        logger.debug("loading player with sound: %s" % path)

        p = os.path.abspath(path)

        self.playing = False
        self._w = wave.open(p)

        self._player = aa.PCM(aa.PCM_PLAYBACK, aa.PCM_NORMAL)
        self._player.setchannels(self._w.getnchannels())
        self._player.setrate(self._w.getframerate())
        self._player.setformat(aa.PCM_FORMAT_S16_LE)
        self._player.setperiodsize(self._periodsize)

        self._t = threading.Thread(target=self._run)
Пример #12
0
    def select_next_pending(self):
        """
		Select and set the next pending alarm.
		"""
        if not (len(self.pool) > 0):
            logger.warning("found no alarms... exiting")
            sys.exit(1)

        date = get_date()
        lowest = self.pool[0]

        for a in self.pool:
            logger.debug("] %s" % str(a.time_pending()))

        for alarm in self.pool:
            if alarm.time_pending() < lowest.time_pending():
                lowest = alarm

        logger.info("next pending alarm (%s) @%s" %
                    (lowest.name, str(lowest.time_pending())))
        self.next_pending = lowest
        return lowest
Пример #13
0
    def load(self):
        """
		Loads the alarms, duuh
		"""
        if os.path.isfile(os.path.abspath(self.alarm_file)):
            logger.debug("alarms found @ %s" % self.alarm_file)
        else:
            logger.critical("could not find %s \n... exiting" %
                            self.alarm_file)
            sys.exit(1)

        alarm_json = self._get_json(self.alarm_file)
        al = []

        for k in alarm_json:
            o = alarm_json[k]
            a = Alarm(k, o["label"], int(o["hour"]), int(o["minute"]),
                      o["days"], o["options"])
            al.append(a)
        self.pool = al

        logger.debug("loaded %d alarms..." % len(self.pool))
Пример #14
0
    def _play_queries(self, delay, sounds):
        """
		Itterates over a given list of queries and plays them
		with a given delay after each one.
		"""
        logger.debug("playing query queue...")

        p = Player()
        idx = 0
        maxidx = len(sounds)

        while idx < maxidx:
            p.load(sounds[idx])
            logger.debug("playing and then delaying for %d seconds..." % delay)

            p.play(delay, True)
            idx += 1

        logger.debug("played queue successfully...")