# -*- coding: utf-8 -*-
from __future__ import division
from ..__load__ import *
from .base import Base
import subprocess

class Sox(Base):
	def __init__(self, **kwargs):
		super(self.__class__, self).__init__(**kwargs)
		self.playing = False
		self.pipe = None
		self.delete = False
		self.volume = 1
		self.onCompleteds = []

	def run(self):
		cmd = ['play', '-v', str(self.volume), str(self.src)]
		cmd = ['aplay', str(self.src)]
		self.logger.info(self.mouth.log('播放语音 ' + ' '.join(cmd)))

		self.proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		self.playing = True
		self.proc.wait()
		self.playing = False
		if self.delete:
			File.remove(self.src)
		self.logger.info(self.mouth.log('播放完成'))
		for onCompleted in self.onCompleteds:
			if onCompleted:				
				onCompleted()
		self.onCompleteds = []

	def play(self, src, delete=False, onCompleted=None, volume=1):
		self.src = src		
		self.delete = delete
		self.onCompleteds.append(onCompleted)
		self.volume = volume
		self.start()

	def appendOnCompleted(self, onCompleted):
		if onCompleted:
			self.onCompleteds.append(onCompleted)

	def play_block(self):
		self.run()

	def stop(self):
		if self.proc:
			self.onCompleteds = []
			self.proc.terminate()
			if self.delete:
				File.remove(self.src)

	def is_playing(self):
		return self.playing