Я относительно новичок в Python и pygame, и столкнулся с проблемой. Я удалил большую часть своего кода, просто оставив функцию и нажав клавишу, вызывающую эту функцию, чтобы выделить проблему.
Кстати, я слепой, поэтому вопрос связан со звуком... и моя основная задача Первоначальной целью является манипулирование звуком, прежде чем переходить к визуальным эффектам.
У меня есть вещи, которые панорамируют звук влево/вправо, вправо/влево, в случайном порядке, увеличивают и т. д., создавая звуковую среду. Все работает хорошо и во все можно играть вместе. У меня возникла следующая проблема:
Если в приведенной ниже функции звук панорамируется справа налево, и я останавливаю его, скажем, на полпути, при следующем запуске звук будет играю дважды. Один раз с того места, где я остановился... и еще раз с самого начала. Я хочу остановить его, но если я запущу его снова, он снова начнется с правой стороны.
Например, если этот звук похож на звук инопланетянина, я могу выстрелить в него. вниз, и при следующем запуске функция будет корректно запускаться с правой стороны.
Как я уже сказал, я относительный новичок, учусь около 4 или 5 месяцев, поэтому возможно, есть некоторые явные проблемы, особенно, возможно, с концепцией многопоточности? Ключевым моментом является наличие всего аудио, доступного для одновременного воспроизведения, если это необходимо, а не ожидание завершения цикла... и все, что у меня есть, работает таким образом, за исключением вышеупомянутых проблем, которые мне нужно решить. Будем очень признательны за любую помощь/совет.
import pygame
import time
import sys
import random
import threading
import accessible_output2.outputs.auto
# initialize pygame
pygame.init ()
# create an output for accessible output2
output = accessible_output2.outputs.auto.Auto()
# set the screen size
screen_width = 1600
screen_height = 900
screen_colour = 255, 255, 255
screen = pygame.display.set_mode ((screen_width, screen_height))
# set a caption/title for the window
pygame.display.set_caption ("Sound manipulation in pygame latest")
# initialize the pygame mixer
pygame.mixer.init ()
# audio files
example_audio = pygame.mixer.Sound ("sounds\example.wav")
# set initial volume to the centre
vol_left = 1.0
vol_right = 1.0
# list of volume levels for the random pan
# will also be used for regular panning left and right for targets
target_vol_l = [
0.00, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50,
0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95, 1.0
]
# rectangle at the bottom of the screen info
rect_colour = 0, 0, 0
rect_width = 200
rect_height = 50
rect_x = 800
rect_y = 850
rect_1 = pygame.Rect (rect_x, rect_y, rect_width, rect_height)
rect_1.center = (rect_x, rect_y)
# circle in the middle of the window
circle_colour = 0, 0, 0
circle_x = 800
circle_y = 750
circle_radius = 100
# Initialize the clock
clock = pygame.time.Clock()
def auto_pan_left (audio_file, channel_num, loop=0, sleep_time = 1.00):
"""
pans left and auto Plays audio files passed with a path and channel number
loop is optional
"""
sound = audio_file
channel = pygame.mixer.Channel(channel_num)
channel.play(sound, loops=loop)
# Flag to indicate if panning operation is complete
panning_complete = False
# this is an object generator within the above function
def change_pan_position():
nonlocal panning_complete
index_plus = 0
index_minus = 20
try:
while not panning_complete:
left_volume = target_vol_l[index_plus]
right_volume = target_vol_l[index_minus]
channel.set_volume(left_volume, right_volume)
# move from right to left in passed intervals
time.sleep(sleep_time)
index_plus+= 1
index_minus-= 1
# check to see if the panning is complete
if index_plus == len(target_vol_l) and index_minus < 0:
# the panning was successful
panning_complete = True
stop_sound_channels(channel_num)
except Exception as e:
output.speak ("auto left panning failed")
# Start a thread to pan the sound
stereo_thread = threading.Thread(target=change_pan_position)
stereo_thread.daemon = True # Daemonize the thread so it will be automatically killed when the program exits
stereo_thread.start()
def stop_sound_channels (channel_num):
"""
stops audio files passed with a channel number
"""
# the channel
sound_channel = pygame.mixer.Channel (channel_num)
# stop the sound
sound_channel.stop ()
# main game loop
running = True
while running:
for event in pygame.event.get ():
if event.type == pygame.quit:
running = False
pygame.quit ()
sys.exit ()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q or event.key == pygame.K_ESCAPE:
pygame.quit ()
sys.exit ()
elif event.key == pygame.K_p:
auto_pan_left (example_audio, 1, -1, 1.00)
elif event.key == pygame.K_s:
stop_sound_channels (1)
# display stuff
screen.fill (screen_colour)
# draw the rectangle at the bottom of the screen
# we defined it's properties nearer the top
# we will move it left/right
pygame.draw.rect (screen, rect_colour, rect_1)
pygame.draw.circle (screen, (circle_colour), (circle_x, circle_y), circle_radius)
# flip the screen
pygame.display.flip ()
# Cap the frame rate
clock.tick(60)
Подробнее здесь: https://stackoverflow.com/questions/783 ... en-panning