You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何winsound.PlaySound无法播放指定文件中的音频?

问题原因

winsound.PlaySound() 仅支持WAV格式音频以及Windows系统内置声音,完全不兼容OGG格式——这就是你播放无声音的核心原因。你的OGG文件在普通播放器能正常播放,但PlaySound无法解码这种格式。

解决方案

方案1:转换音频格式为WAV

把morse_dot.ogg和morse_dash.ogg转换成WAV格式(用Audacity、格式工厂等工具免费转换即可),然后修改代码里的文件名后缀为.wav,直接用原PlaySound逻辑就能正常播放。

方案2:用支持多格式的音频库播放OGG

如果不想转格式,换用playsound或pygame这类支持OGG的库:

方法A:使用playsound库

  1. 先安装稳定版本:
pip install playsound==1.2.2
  1. 修改代码的播放逻辑:
from playsound import playsound
import time

# 替换原winsound相关代码
path = "./"  # 改为音频文件实际所在路径,同目录用./即可

# 仅在编码后播放声音(解码结果是明文,不需要播放)
if ask == 1 and "invalid" not in result:
    for char in result:
        if char == ".":
            playsound(path + "morse_dot.ogg")
            time.sleep(0.2)  # 加间隔避免声音重叠
        elif char == "-":
            playsound(path + "morse_dash.ogg")
            time.sleep(0.4)
        elif char == "/":
            time.sleep(0.6)  # 空格对应单词间隔
        elif char == " ":
            time.sleep(0.2)  # 字符间间隔

方法B:使用pygame库

  1. 安装库:
pip install pygame
  1. 修改代码:
import pygame
import time

pygame.mixer.init()
# 预先加载音频,避免重复读取文件
dot_sound = pygame.mixer.Sound("morse_dot.ogg")
dash_sound = pygame.mixer.Sound("morse_dash.ogg")

# 仅在编码后播放
if ask == 1 and "invalid" not in result:
    for char in result:
        if char == ".":
            dot_sound.play()
            time.sleep(0.2)
        elif char == "-":
            dash_sound.play()
            time.sleep(0.4)
        elif char == "/":
            time.sleep(0.6)
        elif char == " ":
            time.sleep(0.2)

额外代码修复点

  1. 路径错误:原代码里path = "*/"是无效路径,改为实际路径,比如同目录用"./",绝对路径用"C:/morse_sounds/"(注意用正斜杠或双反斜杠)。
  2. 播放逻辑优化:原代码会对解码后的明文执行播放,这完全没必要,只在编码后播放摩斯码即可。
  3. 拼写错误:原代码里的charecter、knowladge、inpput是拼写错误,建议修正,避免后续维护混淆。

修改后的完整代码示例(playsound版本)

from playsound import playsound
import pyperclip as pc
import time

morse_code_dictionary = {'A': '.-', 'B': '-...',
                         'C': '-.-.', 'D': '-..', 'E': '.',
                         'F': '..-.', 'G': '--.', 'H': '....',
                         'I': '..', 'J': '.---', 'K': '-.-',
                         'L': '.-..', 'M': '--', 'N': '-.',
                         'O': '---', 'P': '.--.', 'Q': '--.-',
                         'R': '.-.', 'S': '...', 'T': '-',
                         'U': '..-', 'V': '...-', 'W': '.--',
                         'X': '-..-', 'Y': '-.--', 'Z': '--..',
                         '1': '.----', '2': '..---', '3': '...--',
                         '4': '....-', '5': '.....', '6': '-....',
                         '7': '--...', '8': '---..', '9': '----.',
                         '0': '-----', ', ': '--..--', '.': '.-.-.-',
                         '?': '..--..', '/': '-..-.', '-': '-....-',
                         '(': '-.--.', ')': '-.--.-', ' ': '/', '': ''}

morse_code_to_alphabet_dictionary = {
    x: y for y, x in morse_code_dictionary.items()}

md, mad = morse_code_dictionary, morse_code_to_alphabet_dictionary


def valid_morse(message):
    char_code_list = message.split(" ")
    return all(char_code in mad for char_code in char_code_list)


def encode():
    text = input("Please input your text here.\n=")
    result = ""
    try:
        for char in text.upper():
            result += md[char] + " "
    except KeyError:
        result = "invalid character input!!!"

    return result


def decode():
    code = input("Enter your code here.\n=")
    result = ""
    if not valid_morse(code):
        result = "Your code was not valid or not in my knowledge. Please try again!!!"
        return result

    for single_char in code.split(" "):
        result += mad[single_char]

    return result.capitalize()


while True:
    ask = input(
        "Do you want to encode or decode?\nTo encode press 1\nTo decode press 2\n=")

    if ask.isdigit():
        ask = int(ask)

        if ask not in [1, 2]:
            print("Invalid input!!!\nTry Again!!!")
            continue

        elif ask == 1:
            result = encode()
            # 编码后播放摩斯码声音
            path = "./"  # 替换为你的音频文件实际路径
            if "invalid" not in result:
                for char in result:
                    if char == ".":
                        playsound(path + "morse_dot.ogg")
                        time.sleep(0.2)
                    elif char == "-":
                        playsound(path + "morse_dash.ogg")
                        time.sleep(0.4)
                    elif char == "/":
                        time.sleep(0.6)
                    elif char == " ":
                        time.sleep(0.2)
        elif ask == 2:
            result = decode()
    break


print(result)
print("Result copied in ClipBoard")
pc.copy(result)

input("Press Enter To Exit")

内容的提问来源于stack exchange,提问作者Safayat Ibrahim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 18:54:25