如何为Python聊天程序的客户端消息接收函数添加提示音
Hey there! Adding a notification sound when your chat app receives a message is such a nice quality-of-life touch—let’s break down a few easy, cross-platform (or OS-specific) ways to implement this right into your existing message-receiving function.
Option 1: Windows Built-in winsound (No Extra Installs)
If your app targets Windows users only, you can use the built-in winsound module—no pip installs required. It’s perfect for quick, simple alerts.
First, define a helper function to play the sound, then call it when a message comes in:
import winsound def play_notification(): # Use a system beep (frequency in Hz, duration in ms) winsound.Beep(1000, 200) # Or play a custom WAV file if you have one: # winsound.PlaySound("notification.wav", winsound.SND_FILENAME | winsound.SND_ASYNC) def receive_message(): # Your existing message-receiving logic here new_message = get_incoming_message() # Replace with your actual message-fetching function if new_message: print(f"New message: {new_message}") # Trigger the notification sound play_notification()
The SND_ASYNC flag lets the sound play in the background so your chat app doesn’t freeze while the alert plays.
Option 2: Cross-Platform playsound (Windows/macOS/Linux)
For a cross-platform solution, the playsound library is super straightforward. First install a reliable version (the latest has minor compatibility quirks):
pip install playsound==1.2.2
Then integrate it into your receive function:
from playsound import playsound def play_notification(): # Use a local WAV/MP3 file (double-check the file path!) try: playsound("notification.mp3", block=False) # block=False plays in background except Exception as e: print(f"Error playing sound: {e}") def receive_message(): # Your existing message logic new_message = get_incoming_message() if new_message: print(f"Received: {new_message}") play_notification()
Option 3: pygame (Ideal if You’re Using a Pygame GUI)
If your chat app uses Pygame for its interface, you can leverage its built-in audio system:
pip install pygame
Set it up once at app startup, then call the sound when needed:
import pygame # Initialize pygame audio once when your app launches pygame.mixer.init() notification_sound = pygame.mixer.Sound("notification.wav") def play_notification(): notification_sound.play() def receive_message(): new_message = get_incoming_message() if new_message: print(f"New message: {new_message}") play_notification()
Pygame handles audio efficiently in the background, so it won’t block your chat app’s functionality.
Quick Pro Tips
- Use absolute file paths for your sound files if you plan to package the app later (avoids path errors).
- Always test the background-play flags (
SND_ASYNC/block=False)—you don’t want your app to hang mid-chat while the sound plays. - If you don’t have a custom sound, system beeps work as a quick fallback for testing.
内容的提问来源于stack exchange,提问作者Sco

