【问题标题】:Error while using pygame keyDown event with pygame mixer将 pygame keyDown 事件与 pygame 混合器一起使用时出错
【发布时间】:2015-12-01 23:36:49
【问题描述】:

所以我试图弄乱Pygame 模块,我使用了pygame.mixerpygame.key。但是,当我运行以下代码块时,它会产生错误。

代码:

import pygame, sys
pygame.mixer.init()

# Assume the sound files exist and are found
kick = pygame.mixer.Sound("kick.wav")
clap = pygame.mixer.Sound("clap.wav")

while True:
    keyPressed = pygame.key.get_pressed()
    if keyPressed[pygame.K_a]:
       pygame.mixer.Sound.play(kick)
    if keyPressed[pygame.K_d]:
       pygame.mixer.Sound.play(clap)

错误信息:

*** error for object 0x101008fd0: pointer being freed was not allocated

任何帮助都会很棒!

【问题讨论】:

  • 我认为您应该使用pygame.init() 来初始化所有模块。
  • 可能操作系统不会向没有窗口的程序发送(键)事件。
  • @furas 它仍然没有工作 - 即使实现了窗口。
  • 你还有同样的错误吗? get_pressed() 需要窗口,但它可能与错误无关。顺便说一句:没有pygame.event.get()get_pressed() 将无法工作。

标签: python-3.x pygame


【解决方案1】:

您的代码无法运行的原因有很多,请参阅下面的我的。

import pygame, sys

pygame.init()

window = pygame.display.set_mode((600,400))

kick = pygame.mixer.Sound("kick.wav")
clap = pygame.mixer.Sound("clap.wav")

while True:
   for event in pygame.event.get():
      if event.type == pygame.KEYDOWN:
         if event.key == pygame.K_a:
            kick.play()
         if event.key == pygame.K_d:
            clap.play()
      if event.type == pygame.QUIT:
         pygame.quit()
         quit()

首先,您必须为pygame创建一个显示窗口才能运行。

window = pygame.display.set_mode((600,400))

第二,请注意您将 Sound 对象分配给 kick 和 clap 变量。这些是具有 play() 方法的 Sound 对象,可以使用点运算符进行引用。这不是错误,只是有点不必要。阅读documentation 以查看 Sound 和 play() 参数。你可以这样做:

kick.play()

最后,一种更传统的事件处理方式。

   for event in pygame.event.get():
       if event.type == pygame.KEYDOWN:
           if event.key == pygame.K_a:

【讨论】:

    【解决方案2】:

    我对您的代码进行了修改尝试,它可以工作 - Linux Mint,Python 2.7.10

    import pygame
    
    pygame.init() # init all modules
    
    window = pygame.display.set_mode((600,400)) # required by event
    
    kick = pygame.mixer.Sound("kick.wav")
    clap = pygame.mixer.Sound("clap.wav")
    
    while True:
        pygame.event.get() # required by get_pressed()
    
        keyPressed = pygame.key.get_pressed()
        if keyPressed[pygame.K_a]:
            print "A"
            pygame.mixer.Sound.play(kick)
        if keyPressed[pygame.K_d]:
            print "D"
            pygame.mixer.Sound.play(clap)
    

    但是你可能有不同的问题,我帮不了你。

    【讨论】:

    • 我指定了 Python 3.x,但是当我在 2.7 下运行它时,这对我有用。感谢您的帮助。
    【解决方案3】:

    这是一个 malloc “双重释放”错误。

    Multiple people 看到了这个错误,看了很多网站后,他们基本上都说了同样的话:

    当您中断调试器时,您会发现对象是什么。只需查找调用堆栈,您就会找到释放它的位置。这将告诉你它是哪个对象。

    设置断点的最简单方法是:

    1. 转到运行 -> 显示 -> 断点(ALT-Command-B
    2. 滚动到列表底部并添加符号malloc_error_break

    以上是链接中接受的答案。

    【讨论】:

    • 似乎对我不起作用...不过还是感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2022-06-25
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多