def recode(seconds): r""" 录音接口 :param seconds: :param file_name: :return: 录音文件名 """ system = platform.platform().split('-')[0] if system == "Windows": import pyaudio CHUNK = 512 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 16000 RECORD_SECONDS = seconds WAVE_OUTPUT_FILENAME = resolve(__file__, "../../output/audios/%s.wav" % str(datetime.now().timestamp())) p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) debug(f"***************start recording {seconds}秒*********************") frames = [] for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK) frames.append(data) debug("*****************done recording******************") stream.stop_stream() stream.close() p.terminate() wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb') wf.setnchannels(CHANNELS) wf.setsampwidth(p.get_sample_size(FORMAT)) wf.setframerate(RATE) wf.writeframes(b''.join(frames)) wf.close() return WAVE_OUTPUT_FILENAME elif system == "Linux": WAVE_OUTPUT_FILENAME = resolve(__file__, "../../output/audios/%s.wav" % str(datetime.now().timestamp())) shell_script = " ".join(['arecord ', '-r', str(44100), '-f', 'S16_LE', '-c', '1', '-d', str(seconds), '-t', 'wav', '-D', 'hw:1,0', WAVE_OUTPUT_FILENAME]) print(shell_script) subprocess.run(shell_script, shell=True, check=True, stdout=subprocess.PIPE) return WAVE_OUTPUT_FILENAME
def prompt2audio(): with open(resolve(__file__, "../../configs/prompt.json"), "r", encoding="utf-8") as fr: prompts = json.load(fr) for keyword in prompts.keys(): print(keyword) if keyword not in [ file_name[0:-4] for file_name in os.listdir( r"F:\codingSpace\Python\rspi\static\audios") ]: path = text2audio( prompts[keyword], resolve(__file__, "../../static/audios/%s.mp3" % keyword)) play_mp3(path)
def clear_audios(max_count=10): clear_dir = resolve(__file__, "../../output/audios/") files = [os.path.join(clear_dir, f) for f in os.listdir(clear_dir)] files.sort(key=lambda x: os.path.getctime(x)) if len(files) >= max_count: for file in files[0:10]: try: os.remove(file) except PermissionError as pe: debug(f"文件使用中, 文件: {file}") except FileNotFoundError as fnfe: debug(f"文件找不到: {file}")
def save_music(music): if music is None: debug("保存的歌曲为空") elif music["filePath"]: debug("已存在") return music["filePath"] file_name = "%s-%s.mp3" % (music["name"], music["singer"]) with request.urlopen(url=music["downloadLink"]) as gr: data = gr.read() file_path = resolve(__file__, "../../output/music/%s" % file_name) with open(file_path, "wb+") as fw: fw.write(data) return file_path
def search_music(music_name): musics = os.listdir(resolve(__file__, "../../output/music/")) for music in musics: result = pattern.match(music) if result and result.group(1) == music_name: print(music_name) return { "name": result.group(1), "singer": result.group(2), "downloadLink": None, "filePath": os.path.abspath(os.path.join("../../output/music/", music)) } search_url = "%s%s" % (music_cfg["search_url"], quote(music_name)) with request.urlopen(url=search_url) as gr: rs = json.loads(gr.read().decode("utf-8")) print(rs) if not rs["success"]: debug("搜索歌曲%s失败" % music_name) return None first_song_name = rs["songList"][0]["name"] first_song_singer = rs["songList"][0]["artists"][0]["name"] first_song_id = rs["songList"][0]["id"] get_url = music_cfg["get_url"] query_str = (music_cfg["vendor"][0], first_song_id, music_cfg["query"]["raw"], music_cfg["query"]["br"]) get_url += "%s?id=%s&row=%s&br=%d" % query_str with request.urlopen(get_url) as gr: rs = json.loads(gr.read().decode("utf-8")) if rs["success"]: return { "name": first_song_name, "singer": first_song_singer, "downloadLink": rs["url"], "filePath": None } else: debug("请求歌曲%s下载连接失败, id: %d" % (music_name, first_song_id))
def _loop_photograph(duration): r""" 循环拍照任务 :param duration: :return: """ camera = PiCamera() camera.resolution = (1024, 768) camera.start_preview() # Camera warm-up time sleep(2) count = 1 while True: sleep(duration) print("开始第%d次拍照" % count) count += 1 now_time_str = datetime.now().strftime("%Y-%m-%d-%H-%M-%S") img_path = resolve(__file__, '../../output/photos/%s.jpg' % now_time_str) camera.capture(img_path) print("开始发送邮件") mail(img_path)
def take_photo(camera): now_time_str = datetime.now().strftime("%Y-%m-%d-%H-%M-%S") img_path = resolve(__file__, '../../static/photos/%s.jpg' % now_time_str) print("开始拍照...") camera.capture(img_path) return img_path
def get_file_path(text): md5 = hashlib.md5() md5.update(text.encode('utf-8')) file_name = md5.hexdigest() return resolve(__file__, "../../output/audios/%s.mp3" % file_name)
import hmac import hashlib import time from urllib import request, parse from utils.tpath import resolve logging.basicConfig(level=logging.DEBUG) debug = logging.debug __author__ = 'LY' ''' ''' arc_cfg = json.load( open(resolve(__file__, "../../configs/arc.json"), "r", encoding="utf-8")) def audio_recognize(audio_path): size = os.path.getsize(audio_path) timestamp = time.time() string_to_sign = arc_cfg["httpMethod"] + "\n" + arc_cfg["httpUri"] + "\n" + arc_cfg["key"] + "\n" +\ arc_cfg["dataType"] + "\n" + arc_cfg["signatureVersion"] + "\n" + str(timestamp) sign = base64.b64encode( hmac.new(arc_cfg["key"].encode("utf-8"), string_to_sign.encode("utf-8"), digestmod=hashlib.sha1).digest()) data = parse.urlencode([('access_key', arc_cfg["key"]), ('sample_bytes', size), ('timestamp', str(timestamp)), ('signature', sign),
def request_music(): play_mp3(resolve(__file__, "../../static/audios/点歌.mp3")) text = voice2txt() play_by_search(text)