【问题标题】:Trying to play a sound wave on python using pygame尝试使用 pygame 在 python 上播放声波
【发布时间】:2020-11-22 02:39:01
【问题描述】:

我正在遵循“程序员数学”一书中的这个例子,但它对我不起作用:

import pygame, pygame.sndarray
    
pygame.mixer.init(frequency=44100, size=-16, channels=1)
    
import numpy as np
    
arr = np.random.randint(-32768, 32767, size=44100)
    
sound = pygame.sndarray.make_sound(arr)
    
sound.play()

它返回这些错误:

... in make_sound return numpysnd.make_sound(array)"
... in make_sound return mixer.Sound(array=array)
ValueError: Array must be 2-dimensionarl for stereo mixer"

代码似乎对作者有用,但我尝试了许多不同的方法来解决它,但都失败了,有什么想法吗?

【问题讨论】:

    标签: python python-3.x numpy pygame


    【解决方案1】:

    pygame.sndarray.array():

    为声音数据创建一个新数组并复制样本。该数组将始终采用从pygame.mixer.get_init() 返回的格式。

    在您的情况下,出于某种原因,混音器似乎创建了具有 2 个声道的立体声格式。您可以通过

    来验证
    print(pygame.mixer.get_init())
    

    使用numpy.reshape 将一维数组转换为二维44100x1 数组。然后使用 numpy.repeat 将 44100x1 数组转换为 44100x2 数组,将第一个通道复制到第二个通道:

    import pygame
    import numpy as np
    
    pygame.mixer.init(frequency=44100, size=-16, channels=1)
    
    size = 44100
    buffer = np.random.randint(-32768, 32767, size)
    buffer = np.repeat(buffer.reshape(size, 1), 2, axis = 1)
    
    sound = pygame.sndarray.make_sound(buffer)
    sound.play()
    pygame.time.wait(int(sound.get_length() * 1000))
    

    或者,您可以为每个通道分别创建随机声音:

    import pygame
    import numpy as np
    
    pygame.mixer.init(frequency=44100, size=-16, channels=1)
    
    size = 44100
    buffer = np.random.randint(-32768, 32767, size*2)
    buffer = buffer.reshape(size, 2)
    
    sound = pygame.sndarray.make_sound(buffer)
    sound.play()
    pygame.time.wait(int(sound.get_length() * 1000))
    

    另见How can I play a sine/square wave using Pygame?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-14
      • 1970-01-01
      • 1970-01-01
      • 2011-02-25
      • 1970-01-01
      相关资源
      最近更新 更多