📜  Python Arcade – 播放音频文件

📅  最后修改于: 2022-05-13 01:55:14.294000             🧑  作者: Mango

Python Arcade – 播放音频文件

在本文中,我们将学习如何使用Python在 Arcade 游戏中播放或添加音频。

播放音频文件

在这个例子中,我们想在玩家触摸屏幕的左端或右端时播放我们的音频。为此,我们将使用街机模块的 2 个功能。

  • arcade.load_sound():我们将使用这个函数来加载我们的音频文件。
  • arcade.play_sound():我们将使用这个函数来播放我们的音频。

在下面的示例中,我们将创建一个 MainGame() 类。首先在这个类中,我们将初始化一些玩家的速度、x 和 y 坐标变量,然后我们将在这个类中创建 2 个函数。

  • on_draw():在这个函数,我们将绘制我们的播放器并开始渲染。
  • on_update():在这个函数,我们将通过增加速度来更新玩家精灵的 x 坐标。之后,如果玩家越过屏幕边界,我们将改变移动方向并使用 play_sound()函数播放音频。

下面是实现:

Python3
# Importing arcade module
import arcade
  
# Creating MainGame class       
class MainGame(arcade.Window):
    def __init__(self):
        super().__init__(600, 600, title="Player Movement")
  
        # Initializing the initial x and y coordinated
        self.x = 250 
        self.y = 250
  
        # Initializing a variable to store
        # the velocity of the player
        self.vel = 300
  
    # Creating on_draw() function to draw on the screen
    def on_draw(self):
        arcade.start_render()
  
        # Drawing the rectangle using
        # draw_rectangle_filled function
        arcade.draw_rectangle_filled(self.x, self.y,50, 50,
                                     arcade.color.GREEN )
    # Creating on_update function to
    # update the x coordinate
    def on_update(self,delta_time):
        self.x += self.vel * delta_time
  
        # Changing the direction of
        # movement if player crosses the screen
        if self.x>=550 or self.x<=50:
            self.vel *= -1
  
            # Loading the audio file
            audio = arcade.load_sound('Audio.mp3',False)
  
            # Printing "Playing Audio"
            print("Playing Audio.mp File")
  
            # Playing the audio
            arcade.play_sound(audio,1.0,-1,False)
              
          
# Calling MainGame class       
MainGame()
arcade.run()


输出: