【问题标题】:how to add sound to a message receiving function如何为消息接收功能添加声音
【发布时间】:2018-08-23 11:25:18
【问题描述】:

我目前正在开发一个基于 Python 的聊天程序,我正在尝试弄清楚如何在用户收到消息时添加通知声音这是客户端的消息接收功能我想做的是我想要当用户收到消息时播放声音

def receive():
    """Handles receiving of messages."""
    while True:
        try:
            msg = client_socket.recv(BUFSIZ).decode("utf8")
            msg_list.insert(tkinter.END, msg)
        except OSError:  # Possibly client has left the chat.
            break

【问题讨论】:

  • 粘贴一些关于您遇到的问题的具体问题的代码。链接你的源代码不会得到任何答案。
  • this example我也许写过。
  • 你真的需要一些标点符号...

标签: python python-3.x tkinter


【解决方案1】:

我们先创建一个播放声音的函数

import playsound

def play():
    ''' Setting second argument to False makes the function run asynchronously. '''
    isSync =  False

    playsound.playsound("/path/to/your/sound/file.mp3",isSync)

'''In your function to handle incoming messages'''
def receive():
"""Handles receiving of messages."""
    while True:
        try:
            msg = client_socket.recv(BUFSIZ).decode("utf8")
            msg_list.insert(tkinter.END, msg)
            play()
        except OSError:  # Possibly client has left the chat.
            break  

阅读更多关于playsound这里https://pypi.python.org/pypi/playsound/1.2.1\

编辑:修复缩进错误

附: :感谢@Nae 建议改进异步部分。

【讨论】:

  • 按预期标记答案(如果它解决了您的目的)将不胜感激。
  • 这可能会在播放声音时阻塞 GUI,将False 作为第二个参数传递,以便异步播放声音
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多