九色国产,午夜在线视频,新黄色网址,九九色综合,天天做夜夜做久久做狠狠,天天躁夜夜躁狠狠躁2021a,久久不卡一区二区三区

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
Python實現(xiàn)可以語音聊天的桌面寵物程序

目錄

簡介

程序

源代碼

GUI

        DesktopWife.py

        MusicPlayer.py

        WeatherGui.py

語音


簡介

        普通的桌面寵物程序只能動一動,于是我給程序添加了語言,既可以聊天,也可以實現(xiàn)一些自動功能,不如搜索,打開程序什么的。


程序


源代碼

        gui界面都是使用PyQt5開發(fā)的,語音喚醒功能也是使用的第三方庫和api   

GUI

        DesktopWife.py

  1. import sys
  2. import os
  3. from PyQt5.QtGui import QCursor
  4. from PyQt5.QtGui import QIcon
  5. from PyQt5.QtGui import QPainterPath
  6. from PyQt5.QtGui import QRegion
  7. from PyQt5.QtGui import QPixmap
  8. from PyQt5.QtCore import Qt
  9. from PyQt5.QtCore import QRectF
  10. from PyQt5.QtCore import QTimer
  11. from PyQt5.QtWidgets import QWidget
  12. from PyQt5.QtWidgets import QApplication
  13. from PyQt5.QtWidgets import QLabel
  14. from PyQt5.QtWidgets import QDesktopWidget
  15. from PyQt5.QtWidgets import QMenu
  16. from PyQt5.QtWidgets import QAction
  17. from PyQt5.QtWidgets import QFileDialog
  18. from PyQt5.QtWidgets import QMessageBox
  19. import requests
  20. import WeatherGui
  21. import MusicPlayer
  22. import Tray
  23. import VoiceToText
  24. VoiceToText.run()
  25. """主界面"""
  26. class DesktopWife(QWidget):
  27. def __init__(self):
  28. super(DesktopWife, self).__init__()
  29. self.UI()
  30. def UI(self):
  31. self.Image = QPixmap(".\image\\bg.png")
  32. self.WindowSize = QDesktopWidget().screenGeometry()
  33. self.setWindowTitle("DesktopWife")
  34. self.resize(int(self.Image.width()), int(self.Image.height()))
  35. self.move(int((self.WindowSize.width() - self.Image.width()) / 2), int((self.WindowSize.height() - self.Image.height()) / 2))
  36. self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.SubWindow)
  37. # setAutoFillBackground(True)表示的是自動填充背景,False為透明背景
  38. self.setAutoFillBackground(False)
  39. # 窗口透明,窗體空間不透明
  40. self.setAttribute(Qt.WA_TranslucentBackground, True)
  41. self.PlayLabel = QLabel(self)
  42. self.PlayLabel.setPixmap(self.Image)
  43. self.WindowMessage = QLabel("我好困", self)
  44. self.WindowMessage.setGeometry(int((self.Image.width() - 80) / 2) + 10, 10, 200, 40)
  45. self.WindowMessage.setStyleSheet("color: white;")
  46. self.setContextMenuPolicy(Qt.CustomContextMenu)
  47. self.customContextMenuRequested.connect(self._WindowMenu)
  48. self.Timer = QTimer()
  49. self.Timer.start(5000)
  50. self.Timer.timeout.connect(self.RandomWindowMessage)
  51. """右鍵菜單"""
  52. def _WindowMenu(self):
  53. self.Menu = QMenu(self)
  54. self.Menu.setStyleSheet("background-color: black; color: white;")
  55. self.WeatherForecastQAction = QAction(QIcon(".\image\Button.png"), u"查看天氣", self)
  56. self.Menu.addAction(self.WeatherForecastQAction)
  57. self.PlayMusicQAction = QAction(QIcon(".\image\Button.png"), u"播放音樂", self)
  58. self.Menu.addAction(self.PlayMusicQAction)
  59. self.StartTray = QAction(QIcon(".\image\\bg.png"), u"退置托盤", self)
  60. self.Menu.addAction(self.StartTray)
  61. self.CloseWindowAction = QAction(QIcon(".\image\Quit.png"), u"退出程序", self)
  62. self.Menu.addAction(self.CloseWindowAction)
  63. self.WeatherForecastQAction.triggered.connect(self.WeatherForecast)
  64. self.PlayMusicQAction.triggered.connect(self.MusicPaly)
  65. self.StartTray.triggered.connect(self.SetTray)
  66. self.CloseWindowAction.triggered.connect(self.ColseWindowActionEvent)
  67. self.Menu.popup(QCursor.pos())
  68. # 圓角
  69. rect = QRectF(0, 0, self.Menu.width(), self.Menu.height())
  70. path = QPainterPath()
  71. path.addRoundedRect(rect, 10, 10)
  72. polygon = path.toFillPolygon().toPolygon()
  73. region = QRegion(polygon)
  74. self.Menu.setMask(region)
  75. def ColseWindowActionEvent(self):
  76. VoiceToText._conent = False
  77. self.close()
  78. sys.exit()
  79. """系統(tǒng)托盤"""
  80. def SetTray(self):
  81. self._Tray = Tray.TrayIcon(self)
  82. self._Tray.show()
  83. self.hide()
  84. """隨機一詩"""
  85. # 因為csdn的智障檢測,這里無法查看
  86. """音樂播放"""
  87. def MusicPaly(self):
  88. self.file, _Type = QFileDialog.getOpenFileName(self, u"選擇音樂文件", f"{os.path.split(__file__)[0]}\\music")
  89. if os.path.isfile(self.file):
  90. self._MusicPlayGui = MusicPlayer.MusicGui(self.file)
  91. self._MusicPlayGui.show()
  92. else:
  93. QMessageBox.information(self, "提示", f"文件:{self.file} 無法識別")
  94. """天氣預報"""
  95. def WeatherForecast(self):
  96. self.WeatherForecastGUI = WeatherGui.WeatherGUI()
  97. self.WeatherForecastGUI.show()
  98. """重寫移動事假,更改鼠標圖標"""
  99. def mousePressEvent(self, event):
  100. if event.button() == Qt.LeftButton:
  101. self.m_flag = True
  102. self.m_Position = event.globalPos() - self.pos() # 獲取鼠標相對窗口的位置
  103. event.accept()
  104. self.setCursor(QCursor(Qt.OpenHandCursor)) # 更改鼠標圖標
  105. def mouseMoveEvent(self, QMouseEvent):
  106. if Qt.LeftButton and self.m_flag:
  107. self.move(QMouseEvent.globalPos() - self.m_Position) # 更改窗口位置
  108. QMouseEvent.accept()
  109. def mouseReleaseEvent(self, QMouseEvent):
  110. self.m_flag = False
  111. self.setCursor(QCursor(Qt.ArrowCursor))
  112. if __name__ == '__main__':
  113. app = QApplication(sys.argv)
  114. Window = DesktopWife()
  115. Window.show()
  116. app.exec_()

        MusicPlayer.py

  1. import os
  2. from PyQt5 import QtMultimedia
  3. from PyQt5.QtGui import QIcon
  4. from PyQt5.QtGui import QRegion
  5. from PyQt5.QtGui import QCursor
  6. from PyQt5.QtGui import QPainterPath
  7. from PyQt5.QtCore import Qt
  8. from PyQt5.QtCore import QUrl
  9. from PyQt5.QtCore import QSize
  10. from PyQt5.QtCore import QRectF
  11. from PyQt5.QtWidgets import QLabel
  12. from PyQt5.QtWidgets import QSlider
  13. from PyQt5.QtWidgets import QWidget
  14. from PyQt5.QtWidgets import QPushButton
  15. from mutagen import File
  16. """音樂播放界面"""
  17. class MusicGui(QWidget):
  18. def __init__(self, _file):
  19. super(MusicGui, self).__init__()
  20. self.file = _file
  21. self.GetMusicIcon()
  22. self.UI()
  23. self.Music = QUrl.fromLocalFile(_file)
  24. self.Content = QtMultimedia.QMediaContent(self.Music)
  25. self.player = QtMultimedia.QMediaPlayer()
  26. self.player.setVolume(100)
  27. self.player.setMedia(self.Content)
  28. def UI(self):
  29. self.setWindowTitle("DesktopWife-MusicPlayGui")
  30. self.resize(240, 135)
  31. self.QuitButton = QPushButton(self)
  32. self.QuitButton.setIcon(QIcon(".\image\MusicQuit.png"))
  33. self.QuitButton.setIconSize(QSize(200, 200))
  34. self.QuitButton.setGeometry(208, 10, 20, 20)
  35. QuitButtonRect = QRectF(0, 0, self.QuitButton.width(), self.QuitButton.height())
  36. QuitButtonPath = QPainterPath()
  37. QuitButtonPath.addRoundedRect(QuitButtonRect, 10, 10)
  38. QuitButtonPolgon = QuitButtonPath.toFillPolygon().toPolygon()
  39. QuitButtonRegion = QRegion(QuitButtonPolgon)
  40. self.QuitButton.setMask(QuitButtonRegion)
  41. self.QuitButton.clicked.connect(self.QuitButtonEvent)
  42. self.WindowMinimizedButton = QPushButton(self)
  43. self.WindowMinimizedButton.setIcon(QIcon(".\image\WindowMinimized.png"))
  44. self.WindowMinimizedButton.setIconSize(QSize(20, 20))
  45. self.WindowMinimizedButton.setGeometry(180, 10, 20, 20)
  46. WindowMinimizedButtonRect = QRectF(0, 0, self.WindowMinimizedButton.width(), self.WindowMinimizedButton.height())
  47. WindowMinimizedButtonPath = QPainterPath()
  48. WindowMinimizedButtonPath.addRoundedRect(WindowMinimizedButtonRect, 10, 10)
  49. WindowMinimizedButtonPolgon = QuitButtonPath.toFillPolygon().toPolygon()
  50. WindowMinimizedButtonRegion = QRegion(WindowMinimizedButtonPolgon)
  51. self.WindowMinimizedButton.setMask(WindowMinimizedButtonRegion)
  52. self.WindowMinimizedButton.clicked.connect(self.SetWindowMin)
  53. self.MusicIconLabel = QPushButton(self)
  54. self.MusicIconLabel.setGeometry(20, 20, 30, 30)
  55. self.MusicIconLabel.setStyleSheet("color: blue;")
  56. if os.path.isfile(".\music\MusicIcon\MusicIcon.jpg"):
  57. self.MusicIconLabel.setIcon(QIcon(".\music\MusicIcon\MusicIcon.jpg"))
  58. self.MusicIconLabel.setIconSize(QSize(30, 30))
  59. else:
  60. self.MusicIconLabel.setText("無法提取音頻圖片")
  61. self.MusicIconLabel.setGeometry(20, 20, 120, 30)
  62. self.MusicNameLabel = QLabel(self)
  63. self.MusicNameLabel.setGeometry(20, int((self.height() - 30) / 2), 250, 30)
  64. self.MusicNameLabel.setStyleSheet("font-size:10px;")
  65. self.MusicNameLabel.setText(os.path.split(self.file)[-1])
  66. self.volume = QSlider(Qt.Horizontal, self)
  67. self.volume.setMinimum(0)
  68. self.volume.setMaximum(100)
  69. self.volume.setValue(50)
  70. self.volume.setTickInterval(5)
  71. self.volume.setTickPosition(QSlider.TicksBelow)
  72. self.volume.setGeometry(10, 100, 150, 30)
  73. self.volume.valueChanged.connect(self.VolumeNumber)
  74. self.VolumeNumberLabel = QLabel(f"{self.volume.value()}", self)
  75. self.VolumeNumberLabel.setGeometry(175, 100, 20, 20)
  76. self.PlayButton = QPushButton(self)
  77. self.PlayButton.setIcon(QIcon(".\image\stop.png"))
  78. self.PlayButton.setIconSize(QSize(200, 200))
  79. self.PlayButton.setGeometry(200, 100, 30, 30)
  80. self.IS_PlayMusic = False
  81. self.PlayButton.clicked.connect(self.PlayButtonEvent)
  82. # 圓角
  83. rect = QRectF(0, 0, self.width(), self.height())
  84. path = QPainterPath()
  85. path.addRoundedRect(rect, 10, 10)
  86. polygon = path.toFillPolygon().toPolygon()
  87. region = QRegion(polygon)
  88. self.setMask(region)
  89. def SetWindowMin(self):
  90. self.setWindowState(Qt.WindowMinimized)
  91. def QuitButtonEvent(self):
  92. self.hide()
  93. if os.path.isfile(".\music\MusicIcon\MusicIcon.jpg"):
  94. os.remove(".\music\MusicIcon\MusicIcon.jpg")
  95. self.player.stop()
  96. def PlayButtonEvent(self):
  97. if self.IS_PlayMusic:
  98. self.PauseMusic()
  99. else:
  100. self.PlayMusic()
  101. def VolumeNumber(self):
  102. self.VolumeNumberLabel.setText(f"{self.volume.value()}")
  103. self.player.setVolume(self.volume.value())
  104. def GetMusicIcon(self):
  105. self.MusicMutagnFile = File(self.file)
  106. try:
  107. self.MusicIconData = self.MusicMutagnFile.tags['APIC:test'].data
  108. with open(".\music\MusicIcon\MusicIcon.jpg", "wb") as wfp:
  109. wfp.write(self.MusicIconData)
  110. except KeyError:
  111. pass
  112. def PlayMusic(self):
  113. self.player.play()
  114. self.PlayButton.setIcon(QIcon(".\image\play.png"))
  115. self.PlayButton.setIconSize(QSize(200, 200))
  116. self.IS_PlayMusic = True
  117. def PauseMusic(self):
  118. self.player.pause()
  119. self.PlayButton.setIcon(QIcon(".\image\stop.png"))
  120. self.PlayButton.setIconSize(QSize(200, 200))
  121. self.IS_PlayMusic = False
  122. """重寫移動事假,更改鼠標圖標"""
  123. def mousePressEvent(self, event):
  124. if event.button() == Qt.LeftButton:
  125. self.m_flag = True
  126. self.m_Position = event.globalPos() - self.pos() # 獲取鼠標相對窗口的位置
  127. event.accept()
  128. self.setCursor(QCursor(Qt.OpenHandCursor)) # 更改鼠標圖標
  129. def mouseMoveEvent(self, QMouseEvent):
  130. if Qt.LeftButton and self.m_flag:
  131. self.move(QMouseEvent.globalPos() - self.m_Position) # 更改窗口位置
  132. QMouseEvent.accept()
  133. def mouseReleaseEvent(self, QMouseEvent):
  134. self.m_flag = False
  135. self.setCursor(QCursor(Qt.ArrowCursor))

        WeatherGui.py

  1. from PyQt5.QtGui import QIcon
  2. from PyQt5.QtGui import QCursor
  3. from PyQt5.QtGui import QRegion
  4. from PyQt5.QtGui import QPainterPath
  5. from PyQt5.QtCore import Qt
  6. from PyQt5.QtCore import QSize
  7. from PyQt5.QtCore import QRectF
  8. from PyQt5.QtWidgets import QWidget
  9. from PyQt5.QtWidgets import QLabel
  10. from PyQt5.QtWidgets import QPushButton
  11. import requests
  12. """天氣查詢界面"""
  13. class WeatherGUI(QWidget):
  14. def __init__(self):
  15. super(WeatherGUI, self).__init__()
  16. self.setWindowTitle("DesktopWife-WeatherGui")
  17. self.resize(470, 270)
  18. # 圓角
  19. rect = QRectF(0, 0, self.width(), self.height())
  20. path = QPainterPath()
  21. path.addRoundedRect(rect, 10, 10)
  22. polygon = path.toFillPolygon().toPolygon()
  23. region = QRegion(polygon)
  24. self.setMask(region)
  25. self.QuitButton = QPushButton(self)
  26. self.QuitButton.setIcon(QIcon(".\image\Quit.png"))
  27. self.QuitButton.setIconSize(QSize(40, 40))
  28. self.QuitButton.setGeometry(400, 10, 40, 40)
  29. QuitButtonRect = QRectF(0, 0, self.QuitButton.width(), self.QuitButton.height())
  30. QuitButtonPath = QPainterPath()
  31. QuitButtonPath.addRoundedRect(QuitButtonRect, 50, 50)
  32. QuitButtonPolygon = QuitButtonPath.toFillPolygon().toPolygon()
  33. QuitButtonRegin = QRegion(QuitButtonPolygon)
  34. self.QuitButton.setMask(QuitButtonRegin)
  35. self.QuitButton.clicked.connect(self.hide)
  36. self.WeatherText = QLabel(self)
  37. self.WeatherText.setGeometry(int((470 - 300) / 2), int((270 - 200) / 2), 300, 200)
  38. self.GetWeather()
  39. def GetWeather(self):
  40. GET = requests.get("# 因為csdn的智障檢測,這里無法查看")
  41. if GET.status_code == 200:
  42. JSON = GET.json()
  43. INFO = JSON['info']
  44. Data = f"城市:{JSON['city']}\n時間:{INFO['date']}" \
  45. + f"\n星期:{INFO['week']}\n天氣:{INFO['type']}" \
  46. + f"\n{INFO['high']}\n{INFO['low']}\n風向:{INFO['fengxiang']}" \
  47. + f"\n風級:{INFO['fengli']}\n主人您要:{INFO['tip']}"
  48. self.WeatherText.setText(Data)
  49. else:
  50. return False
  51. """重寫移動事假,更改鼠標圖標"""
  52. def mousePressEvent(self, event):
  53. if event.button() == Qt.LeftButton:
  54. self.m_flag = True
  55. self.m_Position = event.globalPos() - self.pos() # 獲取鼠標相對窗口的位置
  56. event.accept()
  57. self.setCursor(QCursor(Qt.OpenHandCursor)) # 更改鼠標圖標
  58. def mouseMoveEvent(self, QMouseEvent):
  59. if Qt.LeftButton and self.m_flag:
  60. self.move(QMouseEvent.globalPos() - self.m_Position) # 更改窗口位置
  61. QMouseEvent.accept()
  62. def mouseReleaseEvent(self, QMouseEvent):
  63. self.m_flag = False
  64. self.setCursor(QCursor(Qt.ArrowCursor))

語音

  1. import os
  2. import wave
  3. import pyaudio
  4. import speech_recognition
  5. import speech_recognition as sr
  6. from threading import Thread
  7. import requests
  8. CHUNK = 1024
  9. FORMAT = pyaudio.paInt16
  10. CHANNELS = 1
  11. RATE = 16000
  12. _conent = True
  13. def record_and_recog(wave_out_path, TIME=3):
  14. p = pyaudio.PyAudio()
  15. stream = p.open(format=FORMAT,
  16. channels=CHANNELS,
  17. rate=RATE,
  18. input=True,
  19. frames_per_buffer=CHUNK)
  20. wf = wave.open(wave_out_path, 'wb')
  21. wf.setnchannels(CHANNELS)
  22. wf.setsampwidth(p.get_sample_size(FORMAT))
  23. wf.setframerate(RATE)
  24. for _ in range(0, int(RATE / CHUNK * TIME)):
  25. data = stream.read(CHUNK)
  26. wf.writeframes(data)
  27. stream.stop_stream()
  28. stream.close()
  29. p.terminate()
  30. wf.close()
  31. return wave_out_path
  32. def TTS(Test: str):
  33. GET = requests.get(f"https://tts.youdao.com/fanyivoice?word={Test}&le=zh&keyfrom=speaker-target")
  34. if GET.status_code == 200:
  35. with open(".\\out.mp3", "wb") as wfp:
  36. wfp.write(GET.content)
  37. wfp.close()
  38. FFplay = os.popen(f"cd {os.path.split(__file__)[0]} && ffplay out.mp3 -noborder -nodisp -autoexit")
  39. FFplay.readlines()
  40. return True
  41. else:
  42. return False
  43. def Scanning(Path="C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\"):
  44. _DIRList = []
  45. _File = []
  46. for paths, dirs, files in os.walk(Path):
  47. if dirs:
  48. for dir in dirs:
  49. _DIRList.append(paths+"\\"+dir)
  50. if files:
  51. for file in files:
  52. _File.append(paths+"\\"+file)
  53. return _File
  54. def GoogleTranslate():
  55. global _conent
  56. while _conent:
  57. Rec = sr.Recognizer()
  58. with sr.AudioFile(record_and_recog(".\\test.wav")) as source:
  59. audio = Rec.record(source)
  60. try:
  61. GoogleTranslateText = Rec.recognize_google(audio, language="zh-CN")
  62. except speech_recognition.UnknownValueError:
  63. continue
  64. print(GoogleTranslateText)
  65. if "小雨" in GoogleTranslateText or "小宇" in GoogleTranslateText:
  66. TTS("主人我在聽,請您下達命令")
  67. NewRec = sr.Recognizer()
  68. with sr.AudioFile(record_and_recog(".\\test.wav")) as Newsource:
  69. NewAudio = NewRec.record(Newsource)
  70. try:
  71. Text = Rec.recognize_google(NewAudio, language="zh-CN")
  72. except speech_recognition.UnknownValueError:
  73. continue
  74. print(Text)
  75. # 因為csdn智障檢測,這里無法查看
  76. elif "打開命令行" in Text:
  77. TTS("好的, 主人")
  78. os.popen(f"start cmd")
  79. TTS("已為您打開命令行")
  80. elif "關閉語音功能" in Text or "關閉語音" in Text:
  81. TTS("好的,主人 下次再見")
  82. break
  83. elif "打開" in Text:
  84. TTS("好的, 主人")
  85. ISSTART = False
  86. for _Path in Scanning():
  87. if Text.strip("打開") == os.path.split(_Path)[-1].split(".")[0]:
  88. os.popen(f'"{_Path}"')
  89. print(_Path)
  90. TTS(f"已為您打開 {Text.strip('打開')}")
  91. ISSTART = True
  92. break
  93. if ISSTART:
  94. continue
  95. else:
  96. TTS(f"主人未找到 {Text.strip('打開')}")
  97. elif "關機" in Text:
  98. TTS("主人是否確定要關機呢?")
  99. shotdownRrc = sr.Recognizer()
  100. with sr.AudioFile(record_and_recog(".\\out.mp3")) as shotdowndata:
  101. shotdownAudio = shotdownRrc.record(shotdowndata)
  102. try:
  103. ISSHOTDOWN = Rec.recognize_google(shotdownAudio, language="zh-CN")
  104. except speech_recognition.UnknownValueError:
  105. continue
  106. if ISSHOTDOWN in ["是", "是的", "沒錯", "要"]:
  107. TTS("好的, 主人好好學習呀!")
  108. os.popen("shutdown -s -t 1")
  109. elif ISSHOTDOWN in ["否", "不", "不要", "不關機"]:
  110. TTS("好的, 不進行關機")
  111. else:
  112. TTS("主人,我沒聽懂")
  113. else:
  114. # 因為csdn的智障檢測,這里無法查看
  115. if GET.status_code == 200:
  116. try:
  117. TTS(str(GET.json()['data']['info']['text']).replace("小思", "小雨"))
  118. except TypeError:
  119. continue
  120. def run():
  121. Start = Thread(target=GoogleTranslate)
  122. Start.start()
  123. # Start.join()

使用 Python 實現(xiàn)一個可以語音交流的桌面寵物

本站僅提供存儲服務,所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權內(nèi)容,請點擊舉報。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
python實現(xiàn)小說閱讀器
PyQt5快速入門(三)PyQt5基本窗口組件
【第二節(jié)】PyQt5基本功能
Python PyQt5整理介紹
Python界面(GUI)編程PyQt5工具欄和菜單
新手寫給新手的PyQt 5開發(fā)心得(上)
更多類似文章 >>
生活服務
熱點新聞
分享 收藏 導長圖 關注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服