Example #1
0
    def __init__(self, **kwargs):
        super(MusicSlider, self).__init__(**kwargs)

        # Audio
        mixer.init()
        mixer.set_num_channels(1)
        self.rain = mixer.Sound("media/audio/rain.ogg")
Example #2
0
    def __init__(self):
        self._files = FileResolver()

        # Store keyboard keys and corresponded sounds
        self._key_sound = {}

        # Load keymap settings
        with open(self._files.keymap_path) as f:
            self._keymap = yaml.safe_load(f)

        # Lower buffer to lower sound delay
        mixer.init(44100, -16, 2, 256)
        # Set higher channels number, allows to play many sounds
        # at the same time without stopping previously started ones
        mixer.set_num_channels(20)

        # Get any mono font, if no mono fonts use system default
        fonts = tuple(filter(lambda txt: 'mono' in txt, font.get_fonts()))
        win_font = fonts[0] if fonts else None
        font.init()
        self._font = font.SysFont(win_font, self.FONT_SIZE)

        # Set up the window
        win_height = len(self._keymap) * self.FONT_SIZE + 2 * self.MARGIN
        self._screen = display.set_mode((self.WINDOW_WIDTH, win_height))
        display.set_caption(self.WINDOW_CAPTION)
Example #3
0
def init():
    global colours, tap, pixels, posScan, stepTime, markTime
    global colBuffer, sounds
    # put your own colours here
    colours = [(255, 0, 0), (255, 72, 0), (255, 145, 0), (255, 218, 0),
               (218, 255, 0), (145, 255, 0), (72, 255, 0), (0, 255, 0),
               (255, 255, 255)]
    tap = CalTap()
    pixel_pin = board.D18
    num_pixels = 128
    # RGB or GRB. Some NeoPixels have red and green reversed
    ORDER = neopixel.GRB
    BRIGHTNESS = 0.1  # 0.6 is maximum brightness for 3A external supply
    pixels = neopixel.NeoPixel(pixel_pin,
                               num_pixels,
                               brightness=BRIGHTNESS,
                               auto_write=False,
                               pixel_order=ORDER)
    pixels.fill((0, 0, 0))
    posScan = 0
    stepTime = 0.3
    markTime = time.time()
    colBuffer = [(0, 0, 0)] * 8
    mixer.pre_init(44100, -16, 12, 512)
    mixer.init()
    # change these to other sample names
    soundNames = ["0", "1", "2", "3", "4", "5", "6", "7"]
    # change Marimba to another directory containing your samples
    sounds = [
        mixer.Sound("Marimba/" + soundNames[i] + ".wav")
        for i in range(0, len(soundNames))
    ]
    mixer.set_num_channels(16)
Example #4
0
    def test_set_num_channels(self):
        mixer.init()

        default_num_channels = mixer.get_num_channels()
        for i in range(1, default_num_channels + 1):
            mixer.set_num_channels(i)
            self.assertEqual(mixer.get_num_channels(), i)
 def __init__(self):
     logging.basicConfig(filename="SoundPlayer.log", level=logging.DEBUG)
     mixer.init()
     mixer.set_num_channels(8)
     self.audio_root = "../../sound_effects/animals"
     self.playlist = read_playlist(self.audio_root)
     self.sounds = {}
Example #6
0
def main(argv):
    mixer.init(44100)
    mixer.set_num_channels(20)
    load_res("./res")
    
    app = App()
    app.MainLoop()
Example #7
0
 def initialize_audio_settings(self):
     """Initialize mixer settings."""
     # Allows for other sounds to be played with background music
     mixer.init()
     mixer.set_num_channels(self.audio_channels)
     mixer.music.load('sounds/background_music.wav')
     mixer.music.set_volume(0.75)
Example #8
0
def play_audio(audio):
    mixer.init()
    mixer.music.load(f"{audio}.mp3")
    mixer.music.set_volume(60)
    mixer.set_num_channels(100)
    mixer.music.play(-1)
    # infinite loop
    while True:

        print("Press 'p' to pause, 'r' to resume")
        print("Press 'done' to exit the program")
        query = input()

        if query == 'p':

            # Pausing the music
            mixer.music.pause()
        elif query == 'r':

            # Resuming the music
            mixer.music.unpause()
        elif query == 'done':

            # Stop the mixer
            mixer.music.stop()
            send_to_file(audio)
            break
Example #9
0
def main(argv):
    mixer.init(44100)
    mixer.set_num_channels(20)
    load_res("./res")

    app = App()
    app.MainLoop()
Example #10
0
    def __init__(self) -> None:
        # initialize game objects
        random.seed()
        pygame.init()
        mixer.set_num_channels(64)  # continous fire alone needs 20
        mixer.music.set_volume(0.2)
        pygame.display.set_caption("Euclides")

        # restore hall of fame
        self._hall_of_fame = HallOfFame(HOF_FILE)
        self._hall_of_fame.restore()
        self._hiscore = self._hall_of_fame.hiscore

        # setup scores
        self._score = Score("font/Monofett-Regular.ttf", 40, WHITE, SCORE_POS)
        self._highscore = HiScore("font/Monofett-Regular.ttf", 40, WHITE,
                                  HISCORE_POS)

        # setup sprite groups
        self._fire = Swarm()  # container for player's projectiles
        self._hostile = Wave()  # container for enemy spacecrafts
        self._hostile_fire = Swarm()  # container for enemy projectiles
        self._exploding = Exploding()  # container for exploding spacecrafts
        self._onscreen = OnScreen()  # container for sprites on screen

        # setup sound
        self._engine_startup = mixer.Sound("wav/engine_startup.wav")
        self._engine_startup.set_volume(0.5)
        self._energy_hum = mixer.Sound("wav/energy_hum.wav")
        self._energy_hum.set_volume(0.5)
        self._ship_destroyed_sound = mixer.Sound(EXPLOSION)
        self._ship_destroyed_sound.set_volume(1)

        self._main()
Example #11
0
    def test_set_num_channels(self):
        mixer.init()

        for i in xrange_(1, mixer.get_num_channels() + 1):
            mixer.set_num_channels(i)
            self.assert_(mixer.get_num_channels() == i)

        mixer.quit()
Example #12
0
def init_player(sr):
    pre_init(sr, -16, 1)
    init()
    set_num_channels(4)
    for i in range(4):
        Channel(i).stop()
    wait_for_channels()
    sleep(2)
    def test_set_num_channels(self):
        mixer.init()

        for i in xrange_(1, mixer.get_num_channels() + 1):
            mixer.set_num_channels(i)
            self.assert_(mixer.get_num_channels() == i)

        mixer.quit()
Example #14
0
 def __init__(self):
     self.sound = {}
     self.music = {}
     self.music_channels = {}
     self.channelIndex = 5
     self.MAX_INDEX = 15
     self.loadSound(resources.backgroundSound, 'background', True)
     mixer.set_num_channels(
         self.MAX_INDEX)  # Being safe and getting 15 channels
 def init_vars(self):
     self.num_channels = 10
     mixer.set_num_channels(self.num_channels)
     self.builtinsounds = {}
     self.filesounds = {}
     self.voicesounds = {}
     self.hotlist = []
     if not self.initialized:
         rospy.loginfo('sound_play node is ready to play sound')
Example #16
0
 def init_vars(self):
     self.num_channels = 10
     mixer.set_num_channels(self.num_channels)
     self.builtinsounds = {}
     self.filesounds = {}
     self.voicesounds = {}
     self.hotlist = []
     if not self.initialized:
         rospy.loginfo('sound_play node is ready to play sound')
Example #17
0
    def play(regs):
        set_num_channels(0x10)

        control = ApuControl(regs[15], regs[17])

        # if control.get_triangle_lc_enable() == 1:
        APUPlayState.play_tri(regs)

        APUPlayState.play_pulse(regs, 0)
        APUPlayState.play_pulse(regs, 4)
Example #18
0
def ring_bells(addr, port):
    app_path = getattr(sys, '_MEIPASS',
                       os.path.abspath(os.path.dirname(__file__)))

    config = Config()

    COMMAND_START = config.getint('STRIKE_COMMANDS', 'command_start')
    EXIT = config.getint('STRIKE_COMMANDS', 'exit')
    LOOK_TO = config.getint('STRIKE_COMMANDS', 'look_to')
    GO = config.getint('STRIKE_COMMANDS', 'go')
    BOB = config.getint('STRIKE_COMMANDS', 'bob')
    SINGLE = config.getint('STRIKE_COMMANDS', 'single')
    THATS_ALL = config.getint('STRIKE_COMMANDS', 'thats_all')
    STAND = config.getint('STRIKE_COMMANDS', 'stand_next')

    mixer.init(frequency=8000, channels=1, buffer=256)
    mixer.set_num_channels(8)

    bells = {
    }  # A dict so that bells can be accessed by bell number starting with one

    for ndx in range(1, config.getint('BELLS', 'bells') + 1):
        bells[ndx] = mixer.Sound(app_path + '/data/bell_' + str(ndx) + '.wav')

    look_to = mixer.Sound(app_path + '/data/LookTo.wav')
    go = mixer.Sound(app_path + '/data/Go.wav')
    bob = mixer.Sound(app_path + '/data/Bob.wav')
    single = mixer.Sound(app_path + '/data/Single.wav')
    thats_all = mixer.Sound(app_path + '/data/ThatsAll.wav')
    stand = mixer.Sound(app_path + '/data/Stand.wav')

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind((addr, port))

    while True:
        data, addr = sock.recvfrom(8)
        command = int.from_bytes(data, byteorder)
        if command == EXIT:
            break
        elif command >= COMMAND_START:
            if command == LOOK_TO:
                look_to.play()
            elif command == GO:
                go.play()
            elif command == BOB:
                bob.play()
            elif command == SINGLE:
                single.play()
            elif command == THATS_ALL:
                thats_all.play()
            elif command == STAND:
                stand.play()
        else:
            # Command is just a bell to be played
            bells[command].play()
 def __init__(self, delegate):
     super(SoundController, self).__init__()
     self.logger = logging.getLogger('game.sound')
     try:
         mixer.pre_init(44100,-16,2,1024)
         mixer.init()
         mixer.set_num_channels(32)
     except Exception, e:
         # The import mixer above may work, but init can still fail if mixer is not fully supported.
         self.enabled = False
         self.logger.error("pygame mixer init failed; sound will be disabled: "+str(e))
 def __init__(self, delegate):
     super(SoundController, self).__init__()
     self.logger = logging.getLogger('game.sound')
     try:
         mixer.pre_init(44100, -16, 2, 1024)
         mixer.init()
         mixer.set_num_channels(32)
     except Exception, e:
         # The import mixer above may work, but init can still fail if mixer is not fully supported.
         self.enabled = False
         self.logger.error(
             "pygame mixer init failed; sound will be disabled: " + str(e))
Example #21
0
def init_feedback_sounds(path1, path2):
    """
    Initialize the sounds for alpha and theta feedbacks
    """
    pgmixer.init()
    pgmixer.set_num_channels(4)

    m1 = pgmixer.Sound(path1)
    m2 = pgmixer.Sound(path2)
    m1.set_volume(1.0)
    m2.set_volume(0.0)

    return m1, m2
Example #22
0
    def _InitializeComponents(self, frequency, channels):

        # Initialize pygame.

        font.init()

        display.init()

        mixer.pre_init(frequency)
        mixer.init()
        mixer.set_num_channels(channels)

        mouse.set_visible(False)
Example #23
0
	def preview_notes(self):
		'''
		Previews the self.keys list audibly and visually simultaneously.
		'''
		self.process_H_W()
		self.message('Previewing notes...')
		fn_font=os.path.join(os.path.dirname(os.path.abspath(__file__)),'anthem_soundfonts','font.sf2')
		fn_midi=os.path.join(os.path.dirname(os.path.abspath(__file__)),'preview.mid')
		fn_wav=os.path.join(os.path.dirname(os.path.abspath(__file__)),'preview.wav')
		if get_init() is None: # Checks if pygame has initialized audio engine. Only needs to be run once per instance
			pre_init(fs, -16, 2, 1024)
			init()
			set_num_channels(128) # We will never need more than 128...
		mid=mido.MidiFile()
		track=mido.MidiTrack()
		mid.tracks.append(track)
		mid.ticks_per_beat=1000
		track.append(mido.MetaMessage('set_tempo', tempo=int(1e6)))
		track.append(mido.Message('program_change', program=sound_presets[self.cfg['sound_preset']], time=0))
		for i in range(len(self.keys)):
			track.append(mido.Message('note_on', note=self.keys[i], velocity=100, time=250))
			track.append(mido.Message('note_off', note=self.keys[i], time=250))
		track.append(mido.Message('note_off', note=self.keys[i], time=500))
		mid.save(fn_midi)
		cmd='fluidsynth -ni {} -F {} -r {} {} {} '.format(self.cfg['fluidsynthextracommand'],fn_wav,fs,fn_font,fn_midi)
		os.system(cmd)
		music.load(fn_wav)
		for i in range(len(self.keys)):
			t=time.time()
			self.imW.remove()
			Wtmp=self.data['W_pp'][:,i]
			cmaptmp=self.cmap[i,:-1]
			self.imW=self.Wax2.imshow((Wtmp[:,None]@cmaptmp[None,:]*255/np.max(self.data['W_pp'])).reshape(self.data['W_shape'][0],self.data['W_shape'][1],3).clip(min=0,max=255).astype('uint8'))
			self.canvas_W.draw()
			self.update()
			if i==0:
				music.play(0)
			time.sleep(.5-np.min(((time.time()-t),.5)))
		time.sleep(.5)
		music.unload()
		try:
			os.remove(fn_midi)
			os.remove(fn_wav)
		except OSError as e:
			print("Failed with:", e.strerror)
		self.refresh_GUI()
Example #24
0
def main():
    pygame.mixer.pre_init(44100, -16, 2, 1024 * 3)
    mixer = pygame.mixer
    mixer.init(44100)
    mixer.set_num_channels(10)
    #    mixer.music.load(os.path.join('./choons/', 'ethergrind.xm'))
    #    mixer.music.play(-1)
    sounds = [None] * 15
    sounds[0] = mixer.Sound(os.path.join('./sounds/', 'logo.wav'))
    sounds[1] = mixer.Sound(os.path.join('./sounds/', 'break.wav'))
    sounds[2] = mixer.Sound(os.path.join('./sounds/', 'golds.wav'))
    sounds[3] = mixer.Sound(os.path.join('./sounds/', 'hitground.wav'))
    sounds[4] = mixer.Sound(os.path.join('./sounds/', 'jump.wav'))
    sounds[5] = mixer.Sound(os.path.join('./sounds/', 'pickup.wav'))
    sounds[6] = mixer.Sound(os.path.join('./sounds/', 'throw.wav'))
    sounds[7] = mixer.Sound(os.path.join('./sounds/', 'tite.wav'))
    sounds[8] = mixer.Sound(os.path.join('./sounds/', 'smush.wav'))
    sounds[9] = mixer.Sound(os.path.join('./sounds/', 'cryingoutloud.wav'))
    sounds[10] = mixer.Sound(os.path.join('./sounds/', 'cartblow.wav'))
    sounds[11] = mixer.Sound(os.path.join('./sounds/', 'turnon.wav'))
    screen = pygame.display.set_mode((640, 480))
    #    pygame.display.set_caption("::ethergrind::")
    pygame.mouse.set_visible(False)
    pygame.font.init()
    game = engine.Game()
    flags = 0
    nextfile = False
    editor = False
    filename = ""
    for arg in sys.argv:
        if (nextfile):
            filename = arg
            nextfile = False
            editor = True
        elif (arg == "-f"):
            flags = pygame.fullscreen
        elif (arg == "-e"):
            nextfile = True
    if (editor):
        pygame.display.set_caption("xml level editor")
        game.run(editscreen(game, sounds, mixer, filename), screen)
    else:
        pygame.display.set_caption("Super Bean Kid")
        game.run(titlescreen(game, sounds, mixer), screen)
Example #25
0
    def __init__(self,game,priority=10):
        super(SoundController, self).__init__(game,priority)
        self.logger = logging.getLogger('game.sound')
        try:
            mixer.pre_init(frequency=22050, size=-16, channels=2, buffer=256)  #256 prev
            mixer.init()
            mixer.set_num_channels(8)

            self.queue=deque() #for queing up quotes

            mixer.set_reserved(CH_MUSIC_1)
            mixer.set_reserved(CH_MUSIC_2)
            mixer.set_reserved(CH_VOICE)

            #mixer.Channel(CH_VOICE).set_endevent(pygame.locals.USEREVENT)  -- pygame event queue really needs display and cause a ton of issues, creating own

        except Exception, e:
            self.logger.error("pygame mixer init failed; sound will be disabled: "+str(e))
            self.enabled = False
Example #26
0
    def __init__(self, screen_size_, channels_: int = 8):
        """

        :param screen_size_: pygame.Rect; Size of the active display
        :param channels_   : integer; number of channels to reserved for the sound controller
        :return            : None
        """

        if not isinstance(screen_size_, pygame.Rect):
            raise ValueError(
                "\n screen_size_ argument must be a pygame.Rect type, got %s "
                % type(screen_size_))
        if not isinstance(channels_, int):
            raise ValueError(
                "\n channels_ argument must be a integer type, got %s " %
                type(channels_))

        assert channels_ >= 1, "\nArgument channel_num_ must be >=1"

        if pygame.mixer.get_init() is None:
            raise ValueError(
                "\nMixer has not been initialized."
                "\nUse pygame.mixer.init() before starting the Sound controller"
            )

        self.channel_num = channels_  # channel to init
        self.start = mixer.get_num_channels(
        )  # get the total number of playback channels
        self.end = self.channel_num + self.start  # last channel
        mixer.set_num_channels(
            self.end)  # sets the number of available channels for the mixer.
        mixer.set_reserved(
            self.end)  # reserve channels from being automatically used
        self.channels = [
            mixer.Channel(j + self.start) for j in range(self.channel_num)
        ]  # create a channel object for controlling playback
        self.snd_obj = [None
                        ] * self.channel_num  # list of un-initialised objects
        self.channel = self.start  # pointer to the bottom of the stack
        self.all = list(range(
            self.start, self.end))  # create a list with all channel number
        self.screen_size = screen_size_  # size of the display (used for stereo mode)
Example #27
0
    def player_play(self) -> None:
        # self.sliders_enable()
        if self.current_album:
            self.ui.setWindowTitle(
                f"{self.current_album.title} - {WindowProp.TITLE}")
        self.player_status = PlayerStatus.PLAYING
        self.ui.btn_pause_play.setIcon(
            QtGui.QIcon(
                str(Path(BASE_PATH, self.cfg.svg_path,
                         self.cfg.svg_btn_pause))))
        self.ui.btn_pause_play.clicked.disconnect()
        self.ui.btn_pause_play.clicked.connect(self.player_pause)
        f_len = len(self.current_album.files)
        pmixer.init(frequency=22050, size=-16, channels=4)
        pmixer.set_num_channels(f_len)
        self.used_channels = []
        for ch in self.current_album.files:
            slider = getattr(self.ui, "vertical_slider_%da" % ch.channel)
            slider.setToolTip("")
            slider.setDisabled(True)
            if os.path.isfile(ch.file):
                slider.setToolTip(ch.title)
                slider.setDisabled(False)
                pmixer.Channel(ch.channel).play(pmixer.Sound(ch.file),
                                                loops=-1)
                position = slider.value()
                pmixer.Channel(ch.channel).set_volume(
                    self.position_to_volume(position))
                self.used_channels.append(ch.channel)
            else:
                self.alert_message(header="Missing File",
                                   text=f"File does not exist:\n {ch.file}")

        for ch in range(0, MAX_NUM_CHANNELS):
            if ch not in self.used_channels:
                slider = getattr(self.ui, "vertical_slider_%da" % ch)
                slider.setToolTip("")
                slider.setDisabled(True)
Example #28
0
import time
mixer.init(frequency=22050, size=-16, channels=2, buffer=128)

musicLoad = mixer.music.load
musicPlay = mixer.music.play
musicStop = mixer.music.stop
musicPause = mixer.music.pause
musicUnpause = mixer.music.unpause
musicFade = mixer.music.fadeout
musicSetVolume = mixer.music.set_volume
musivVolume = mixer.music.get_volume
musicIsPlay = mixer.music.get_busy
musicSetPos = mixer.music.set_pos
musicPos = mixer.music.get_pos

mixer.set_num_channels(16)
twoHands = 1
__hitsounds = {
    'l1': mixer.Sound("sfx/hit0.wav"),
    'l2': mixer.Sound("sfx/hit1.wav"),
    'l3': mixer.Sound("sfx/hit2.wav"),
    'l4': mixer.Sound("sfx/hit3.wav"),
    'r1': mixer.Sound("sfx/hit0.wav"),
    'r2': mixer.Sound("sfx/hit1.wav"),
    'r3': mixer.Sound("sfx/hit2.wav"),
    'r4': mixer.Sound("sfx/hit3.wav")
}
__startsound = mixer.Sound("sfx/start.wav")
__beepSound = mixer.Sound("sfx/beep.wav")
__errorSound = mixer.Sound("sfx/error.wav")
Example #29
0
import sched
import os

from gpiozero import PWMLED
from gpiozero import LoadAverage, PingServer

# sound config
try:
    import contextlib
    with contextlib.redirect_stdout(
            None):  # disabled de irritante welkom tekst van pygame
        from pygame import mixer
except:
    from pygame import mixer
mixer.init()
mixer.set_num_channels(50)  # default is 8
from PIL import Image
from PIL import ImageChops

# white LEDS
led = PWMLED(20)
led.value = 0  #0..1

# heat
hotRes = PWMLED(16)
hotRes.value = 0  #0..1

# addressable LEDS
from neopixel import *
LED_COUNT = 200  # Number of LED pixels.
LED_PIN = 13  # GPIO pin connected to the pixels (18 uses PWM!).
Example #30
0
def run_game():
    # Game parameters
    SCREEN_WIDTH, SCREEN_HEIGHT = 400, 400
    BG_COLOR = 150, 150, 80
    CREEP_FILENAMES = [
        'bonehunter2.png', 
        'skorpio.png',
        'tuma.png', 
        'skrals.png',
        'stronius1.png',
        'stronius2.png',
        'metus_with_guards.png']
    TOWER_FILENAMES = [
        'matanui.png',
        'malum.png',
        'gresh.png',
        'gelu.png',
        'vastus.png',
        'kiina.png',
        'ackar.png',
        'straak.png'
        ]
    SELL_FILENAME = 'Sell.png'
    RAIN_OF_FIRE = 'rain_of_fire.png'
    TORNADO = 'tornado.png'
    TORNADO_BIG = 'tornado_big.png'
    BUTTON_FILENAMES = TOWER_FILENAMES + [RAIN_OF_FIRE, TORNADO, SELL_FILENAME]

    money = 643823726935627492742129573207

    mixer.pre_init(44100, -16, 2, 2048) # setup mixer to avoid sound lag
    mixer.init()
    mixer.set_num_channels(30)
    print "mix", mixer.get_num_channels()
    EXPLOSIONS = [mixer.Sound('expl%d.wav'%(i)) for i in range(1, 7)]
    FIRING = [mixer.Sound('fire%d.wav'%(i)) for i in range(1, 4)]
    N_CREEPS = 10
    N_TOWERS = 0

    pygame.init()

    background = pygame.image.load("Background_Level_1.JPG")
    path = pygame.image.load("Path_Level_1.png")
    w, h = background.get_size()
    assert (w, h) == path.get_size()
    sc = min(1024.0/w, 1024.0/h)
    background = pygame.transform.scale(background, (int(w * sc), int(h * sc)))
    path = pygame.transform.scale(path, (int(w * sc), int(h * sc)))
    backgroundRect = background.get_rect()

    starts, paths = create_paths(path)

    screen = pygame.display.set_mode(
        background.get_size(), 0, 32)
    clock = pygame.time.Clock()

    # Create N_CREEPS random creeps.
    creeps = []    
    for i in range(N_CREEPS):
        creeps.append(Creep(screen,
                            choice(CREEP_FILENAMES), 
                            (   choice(starts)[::-1]), # reversed x and y
                            (   choice([-1, 1]), 
                                choice([-1, 1])),
                            0.05,
                            paths,
                            choice(EXPLOSIONS)))

    towers = [Tower(screen,
                    choice(TOWER_FILENAMES),
                    (randint(0, background.get_size()[0]), randint(0, background.get_size()[1])),
                    (1, 1),
                    0.0,
                    paths, radius=100, max_attacks=3, firing_sounds=FIRING) for i in range (N_TOWERS)]

    buttons = [Button(screen,
                      buttonfile,
                      (randint(0, background.get_size()[0]), randint(0, background.get_size()[1])),
                      (1, 1),
                      0.0,
                      paths) for buttonfile in BUTTON_FILENAMES]



    rightedge = screen.get_width() - 5
    for b in buttons[:len(buttons)//2]:
        b.pos = vec2d(rightedge - b.image.get_width() / 2, 5 + b.image.get_height() / 2)
        rightedge -= (b.image.get_width() + 5)
    rightedge = screen.get_width() - 5
    for b in buttons[len(buttons)//2:]:
        b.pos = vec2d(rightedge - b.image.get_width() / 2, 5 + b.image.get_height() / 2 + 80)
        rightedge -= (b.image.get_width() + 5)

    next_tower = TOWER_FILENAMES[0]

    cursor = Cursor(screen, TOWER_FILENAMES[0],
                    (0, 0),
                    (1,1),
                    0.0, paths)

    font = pygame.font.SysFont(pygame.font.get_default_font(), 20, bold=True)

    tornado_img = pygame.image.load(TORNADO_BIG).convert_alpha()

    global_attacks = GlobalAttacks(screen, RAIN_OF_FIRE,
                                   (randint(0, background.get_size()[0]), randint(0, background.get_size()[1])),
                                   (1, 1),
                                   0.0,
                                   paths, radius=100, max_attacks=3, firing_sounds=FIRING)

    # The main game loop
    #
    rect = pygame.Rect((1, 1), (10, 10))
    selling = False    
    while True:
        # Limit frame speed to 50 FPS
        #
        time_passed = clock.tick(50)
        
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit_game()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    rect.center = pygame.mouse.get_pos()
                    collided = False
                    for b in buttons:
                        if b.rect.colliderect(rect):
                            selling = (b.img_filename == SELL_FILENAME)
                            rain_of_fire = (b.img_filename == RAIN_OF_FIRE)
                            tornado = (b.img_filename == TORNADO)
                            buying = (not selling) and (not rain_of_fire)
                            if buying:
                                next_tower = BUTTON_FILENAMES[buttons.index(b)]
                                cursor.change_image(next_tower)
                            # only one rain of fire available at a time
                            if global_attacks.ready():
                                if rain_of_fire:
                                    for i in range(20):
                                        target = choice(creeps)
                                        global_attacks.target(target)
                            if tornado:
                                targets = [choice(creeps) for i in range(20)]
                                tornado_attack = MobileAttack(global_attacks, 
                                                              targets, 
                                                              img=tornado_img, 
                                                              pos=vec2d((randint(0, background.get_size()[0]), 
                                                                         randint(0, background.get_size()[1]))))
                                tornado_attack.speed = 0.2
                                global_attacks.add_attack(tornado_attack)
                            collided = True
                    for t in towers:
                        if cursor.rect.colliderect(t.rect):
                            collided = t
                    if not collided and not selling and money >= 100:
                        towers += [Tower(screen,
                                         next_tower,
                                         pygame.mouse.get_pos(),
                                         (1, 1),
                                         0.0,
                                         paths,
                                         radius=100,
                                         max_attacks=3,
                                         firing_sounds=FIRING)]
                        money -= 100
                    if selling and collided:
                        if collided in towers:
                            towers.remove(collided)
                            money += 50

        # Redraw the background
        screen.blit(background, backgroundRect)
        
        # Update and redraw all creeps
        for creep in creeps:
            creep.update(time_passed)

        for tower in towers:
            tower.attack(creeps)
            money += tower.update(time_passed)

        money += global_attacks.update(time_passed)
        
        cursor.update()

        for obj in creeps + towers + buttons + [global_attacks, cursor]:
            obj.blitme()
            
        money_text = font.render("%d"%(money), True, pygame.Color(0, 0, 0))
        screen.blit(money_text, (rightedge - 5 - money_text.get_width(), 5 + money_text.get_height()))

        pygame.display.flip()
Example #31
0
mixer.init(frequency=22050, size=-16, channels=2, buffer=128)


musicLoad = mixer.music.load
musicPlay = mixer.music.play
musicStop = mixer.music.stop
musicPause = mixer.music.pause
musicUnpause = mixer.music.unpause
musicFade = mixer.music.fadeout
musicSetVolume = mixer.music.set_volume
musivVolume = mixer.music.get_volume
musicIsPlay = mixer.music.get_busy
musicSetPos = mixer.music.set_pos
musicPos = mixer.music.get_pos

mixer.set_num_channels(16)
twoHands = 1
__hitsounds = {'l1': mixer.Sound("sfx/hit0.wav"), 'l2': mixer.Sound("sfx/hit1.wav"), 'l3': mixer.Sound("sfx/hit2.wav"), 'l4': mixer.Sound("sfx/hit3.wav"),'r1': mixer.Sound("sfx/hit0.wav"), 'r2': mixer.Sound("sfx/hit1.wav"), 'r3': mixer.Sound("sfx/hit2.wav"), 'r4': mixer.Sound("sfx/hit3.wav")}
__startsound = mixer.Sound("sfx/start.wav")
__beepSound = mixer.Sound("sfx/beep.wav")
__errorSound = mixer.Sound("sfx/error.wav")

__acceptsound = mixer.Sound("sfx/accept.wav")
__moveSound = mixer.Sound("sfx/change.wav")
__backSound = mixer.Sound("sfx/back.wav")
__deathSound = mixer.Sound("sfx/death.wav")
__lowHpSound = mixer.Sound("sfx/lowhp.wav")
__damageSound = mixer.Sound("sfx/damage.wav")
__restoreHP = mixer.Sound("sfx/restorehp.wav")

def playDamage():
Example #32
0
 def initialize_audio_settings(self):
     """sound settings"""
     mixer.init()
     mixer.set_num_channels(self.audio_channels)
     self.music_channel.set_volume(0.7)
Example #33
0
 def init_audio(self):
     mixer.init()
     mixer.set_num_channels(8)
     self.voice = mixer.Channel(5)
     self.sound = mixer.Sound(sound_file)
Example #34
0
 def init(self, game):
     mixer.set_num_channels(8)
     mixer.set_reserved(2)
     self.ui_channel = mixer.Channel(0)
     self.bg_channel = mixer.Channel(1)
     self.set_bg(self.load_sound("data/sound/background/Puzzle-Game.wav"))
Example #35
0
import pianohat
import time
from pygame import mixer


def handle_note(channel, pressed):
    if pressed:
        my_sounds[channel].play(loops=0)
        print("You pressed key {}".format(channel))
    else:
        print("You released key {}".format(channel))


mixer.init(22050, -16, 2, 512)
mixer.set_num_channels(13)
my_sound_files = [
    "/home/pi/moo.wav", "/home/pi/dog.wav", "/home/pi/dog.wav",
    "/home/pi/moo.wav", "/home/pi/dog.wav", "/home/pi/moo.wav",
    "/home/pi/dog.wav", "/home/pi/moo.wav", "/home/pi/dog.wav",
    "/home/pi/moo.wav", "/home/pi/dog.wav", "/home/pi/moo.wav",
    "/home/pi/dog.wav"
]
my_sounds = [mixer.Sound(sound_file) for sound_file in my_sound_files]
pianohat.on_note(handle_note)
while True:
    time.sleep(0.001)
Example #36
0
 def __init__(self):
 	'''Initializes mixer, number of channels to 8, and state to not paused'''
 	mixer.init()
     mixer.set_num_channels(8)
     self.paused = False
Example #37
0
except ImportError:
    import android.mixer as mixer

try:
    import android
except ImportError:
    android = None

#pygame 初始化
pygame.init()

ScreenSize = (800, 640)
clock = pygame.time.Clock()

#设置窗口模式及大小
screen = pygame.display.set_mode(ScreenSize)

#鼠标可用
pygame.mouse.set_visible(False)
mixer.set_num_channels(32)

#设置窗口标题
pygame.display.set_caption("放置传奇")

screenwidth = screen.get_width()
screenheight = screen.get_height()

running = True

explosions=0
Example #38
0
if __name__ != '__main__':
    from pygame.mixer import Sound
    from pygame import mixer

    mixer.pre_init(44100, -16, 1, 1000)
    mixer.init()
    mixer.set_num_channels(30)

    sounds = {
        'gun': {
            'shoot': Sound('data/Sounds/gun.wav'),
            'reload': Sound('data/Sounds/gun_reload.wav')
        },
        'ak47': {
            'shoot': Sound('data/Sounds/ak47.wav'),
            'reload': Sound('data/Sounds/ak47_reload.wav')
        },
        'm249': {
            'shoot': Sound('data/Sounds/m249.wav'),
            'reload': Sound('data/Sounds/m249_reload.wav')
        },
        'rifle': {
            'shoot': Sound('data/Sounds/rifle.wav'),
            'reload': Sound('data/Sounds/rifle_reload.wav')
        },
        'shotgun': {
            'shoot': Sound('data/Sounds/shotgun.wav'),
            'reload': Sound('data/Sounds/shotgun_reload.wav')
        },
        'flamethrower': {
            'shoot': Sound('data/Sounds/flamethrower.wav'),
Example #39
0
key_width_extra = (key_rightmost - key_leftmost) % n
key_rightmost = key_rightmost - key_width_extra
key_width = (key_rightmost - key_leftmost) // n
key_height = key_bottommost - key_topmost
key_area = key_height * key_width
threshold_area_value = key_area * 0.1 * 255
key = cv2.resize(cv2.imread('Images/OneWhiteKey.png'), (key_width, key_height),
                 interpolation=cv2.INTER_CUBIC)
#disp("img",key)
#key.shape
PianoImage = np.tile(key, [1, n, 1])
#PianoImage.shape
#disp("piano",PianoImage)
mixer.init()
#mixer.set_num_channels(n)
mixer.set_num_channels(n * 50)
soundList = [
    mixer.Sound("../Music_Notes/" + sounds[i + 1] + '.wav') for i in range(n)
]
yellowTouch = np.zeros([key_height, key_width, 3], dtype="uint8")
yellowTouch[:, :, 0] = 0
yellowTouch[:, :, 1] = 247
yellowTouch[:, :, 2] = 255


def key_Addr():
    keyAddr = []
    prevLeft = key_leftmost
    for i in range(n):
        keyAddr.append([prevLeft, prevLeft + key_width])
        prevLeft = keyAddr[i][1]
import math
from pygame import mixer as mx
from pygame.math import Vector2 as vec

###SETTING VARIABLES
WIDTH = 960
HEIGHT = 544

TITLE = "Slime Invasion"

disp = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption(TITLE)
pg.display.set_icon(pg.image.load('Images/icon.png'))
pg.init()
mx.pre_init(44100, -16, 2, 512)
mx.set_num_channels(16)

sounds = {
    'CrossbowShoot': mx.Sound('Sounds/crossbowsound.wav'),
    'SlimeHit': mx.Sound('Sounds/slimehit.ogg'),
    'SlimeDie': mx.Sound('Sounds/slimedie.wav'),
    'TripleCrossbowShoot': mx.Sound('Sounds/triplecrossbowsound.wav'),
    'CannonShoot': mx.Sound('Sounds/cannonsound.wav'),
    'GameOver': mx.Sound('Sounds/GameOver.wav'),
    'Click': mx.Sound('Sounds/click.wav'),
    'Hover': mx.Sound('Sounds/hover.wav'),
    'WaveStart': mx.Sound('Sounds/WaveStart.wav')
}
music = {
    'Shop': 'Sounds/Loop.wav',
    'Wave': 'Sounds/Loop1.wav',