[英]How can I make a single Button play music, pause music and unpause music in Python using tkinter and pygame?
[英]Pygame - can I make music have an introduction and then a loop point?
我目前正在 Pygame 開發一款游戲,我一直在想辦法讓音樂曲目在不是曲目的開頭的地方循環播放。 所以本質上,它播放一個介紹,然后移動到另一個重復的部分而不重新訪問該介紹。
我想到了幾種幾乎可行的方法,但它們存在問題。
第一個是為介紹和循環部分提供兩個單獨的音頻文件,然后使用pygame.music.set_endevent()
,並在第一個音頻文件完成后加載第二個音頻文件。 這留下了相當明顯的差距並點擊了。
第二個是也使用兩個音頻文件,但在加載第一個文件時排在第二個文件中。 問題在於,對於新排隊的曲目,您似乎無法將播放模式從 0(播放一次)更改為 -1(循環)...
我覺得必須有一種方法可以做到這一點,我真的很感激任何幫助。
在下面的示例中,PyGame 的聲道用於多個音軌。 這里創建了一個事件,以便在 1500 毫秒后播放第二個聲音(與循環曲目同時播放)。
對於您建議的用例,代碼可以在開始時播放介紹音樂,但也可以在將來為/intro-length/毫秒設置一個事件計時器。 當收到該計時器事件時,您的音樂的循環部分可以連續播放,因為介紹應該剛剛停止。 使用多個通道,如果兩個聲音重疊幾毫秒(無聲/淡出)應該無關緊要,只要用戶當然沒有察覺到它,也許在大量的時間上 100% 正確地獲得時間會很棘手不同的系統。 但它應該讓你接近。
請注意,在示例中,聲音已經初始化為 PyGame Sound
對象,我希望這會減少啟動延遲。
import pygame
# Window size
WINDOW_WIDTH = 400
WINDOW_HEIGHT = 400
DARK_BLUE = ( 3, 5, 54)
### initialisation
pygame.init()
pygame.mixer.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) )
pygame.display.set_caption("Multi Sound with Timer")
### sound
# create separate Channel objects for simultaneous playback
channel1 = pygame.mixer.Channel(0) # argument must be int
channel2 = pygame.mixer.Channel(1)
# Rain sound from: https://www.freesoundslibrary.com/sound-of-rain-falling-mp3/ (CC BY 4.0)
rain_sound = pygame.mixer.Sound( 'rain-falling.ogg' )
channel1.play( rain_sound, -1 ) # loop the rain sound forever
# Car Horn sound from: https://www.freesoundslibrary.com/car-horn-sound-effect/ (CC BY 4.0)
horn_sound = pygame.mixer.Sound( 'car-horn.ogg' )
# Create a timer, which will (after the delay-time) post an event to the main loop
pygame.time.set_timer( pygame.USEREVENT, 1500 ) # play the horn in 1500 milliseconds
### Main Loop
clock = pygame.time.Clock()
done = False
while not done:
# Handle user-input
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
done = True
elif ( event.type == pygame.USEREVENT ):
# Timer expired, play the sound
channel2.play( horn_sound )
# Movement keys
#keys = pygame.key.get_pressed()
#if ( keys[pygame.K_UP] ):
# print("up")
# Update the window, but not more than 60fps
window.fill( DARK_BLUE )
pygame.display.flip()
# Clamp FPS
clock.tick_busy_loop(60)
pygame.quit()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.