美文网首页思科DevNet人工智能-AI有趣的python
python 使用 itchat 保存群聊语音并拼接成音频课程

python 使用 itchat 保存群聊语音并拼接成音频课程

作者: NoneLand | 来源:发表于2018-06-26 23:07 被阅读234次

    前言

    我可爱的女朋友上了很多微课,每次整理都费心费时,所以决定用itchat写一个脚本程序,能够自动的保存特定群聊中特定发言人的语音,并使用pydub将保存的语音拼接成音频课程。

    使用步骤:

    1. 在电脑上运行程序:打开命令行,切换到autoRecord.py所在文件夹,然后使用python autoRecord.py
    2. 扫描二维码登录;【根据提示信息,有时只用确认登录即可甚至什么都不用做】
    3. 输入课程相关信息,按照命令行提示输入:1. 课程名称,用以创建文件夹保存语音文件;2. 群名称;3. 发言人名称;首先输入发言人数量,然后依次输入名称;
    4. 命令行提示Start auto replying. 时,就进入自动模式了。只需要在课程结束不需要软件运行时,在手机端的群里面输入结束暗号#END#,电脑程序在拼接音频完成之后,即可在课程文件夹下找到拼接结果文件result.mp3
    5. 如有问题,欢迎来售后。

    工作逻辑

    通过群名和发言人名找到对应的UserName,然后根据UserName判断语音来源,然后根据类型执行相应的操作。在接收到由本微信号在群里面发出的结束暗号时,对语音进行拼接,然后退出程序【目前退出的型式不够优雅】。

    代码

    import itchat
    import os
    from pydub import AudioSegment
    
    @itchat.msg_register([itchat.content.RECORDING, itchat.content.TEXT], isGroupChat=True)
    def download(msg):
        global count, GID, UID, SelfID, FolderName
        if msg['FromUserName'] == GID and msg['ActualUserName'] in UID and msg['Type']=='Recording':
            print("Got Audio:#{} From {}".format(count, msg['ActualNickName']))
            msg['Text']('{}/{}.mp3'.format(FolderName,count))
            count += 1
        if  msg['FromUserName'] == SelfID and msg['ToUserName'] in GID and msg['Type']=='Text' and msg['Text'].startswith('#END#'):
            print("Concat Audio.....")
            AudioConcat(count, FolderName)
            print("Exit! Bye Bye!")
            itchat.logout()
            exit(0)
    
    def AudioConcat(count, FolderName):
        if not count:
            return
        result = AudioSegment.from_mp3('{}/0.mp3'.format(FolderName))
        for i in range(1, count):
            result += AudioSegment.from_mp3('{}/{}.mp3'.format(FolderName, i))
        result.export('{}/{}.mp3'.format(FolderName, 'result'), format='mp3')
    
    def GotInfo():
        print('*'*20)
        while True:
            FolderName = input("Please input Course Name:")
            if os.path.exists(FolderName):
                print("Folder Exists! Try another Name!")
            else:
                os.mkdir(FolderName)
                break
    
        print('*'*20)
        itchat.get_chatrooms(update=True)
        while True:
            GName = input('Please Enter Group Name:')
            G = itchat.search_chatrooms(name=GName)
            if G:
                break
        GID = G[0]['UserName']
    
        print('*'*20)
        G = itchat.update_chatroom(userName=GID, detailedMember=True)
        MList = G['MemberList']
        UID = []
        Unum = int(input("Please input the num of users to be listened:"))
        print("Input UserName one by one!")
        while len(UID)< Unum:
            UName = input('Please input user name:')
            aUID = 0
            for m in MList:
                # print(m['NickName'], m['RemarkName'])
                if UName in [m['NickName'], m['RemarkName']]:
                    aUID = m['UserName']
            if aUID:
                UID.append(aUID)
                print('Added Successfuly:{}'.format(UName))
            else:
                print('Added Failed:{}| Please Check and reinput!'.format(UName))
        print('Listen to @{}@{}'.format(GName, UName))
        SelfID = itchat.get_friends()[0]['UserName']
        return GID, UID, FolderName, SelfID
    if __name__ == '__main__':
        itchat.auto_login(hotReload=True)
        count = 0
        GID, UID, FolderName, SelfID = GotInfo()
        itchat.run()
    

    相关文章

      网友评论

        本文标题:python 使用 itchat 保存群聊语音并拼接成音频课程

        本文链接:https://www.haomeiwen.com/subject/fnrvyftx.html