Ejemplo n.º 1
0
    def __init__(self, config: ConfigReader):
        pygame.init()
        self.headless = config.headless and config.server
        if not self.headless: pygame.display.set_icon(ICON)
        self.actx = None if self.headless else Context(Device())
        self._mute = config.muted

        if config.server:
            self.server = socket()
            self.server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
            self.server.bind((config.host, config.port))
            self.server.listen(1)
            print('Socket server is listening on {}:{}'.format(
                config.host, config.port))
            self.timeout = config.timeout
            self.sockinp = 0, 0, -pi * 3 / 4, 0, 0  # freeze and point to NW
        else:
            self.server = self.sockinp = None

        self.max_fps, self.fps = config.max_fps, config.max_fps
        self.musicvol = config.musicvol
        self.touch = config.touch
        self.key, self.mouse = config.key, config.mouse
        self.maze = Maze(config.max_fps, config.size, config.headless,
                         config.export_dir, 1000 / config.export_rate)
        self.hero = self.maze.hero
        self.clock, self.paused = Clock(), False
Ejemplo n.º 2
0
def play(files: Iterable[str], device: str, reverb: str) -> None:
    """Load and play files on the given device."""
    with Device(device) as dev, Context(dev) as ctx:
        print('Opened', dev.name)
        print('Loading reverb preset', reverb)
        with Source() as src, ReverbEffect(reverb) as fx:
            src.sends[0].effect = fx
            for filename in files:
                try:
                    decoder = decode(filename)
                except RuntimeError:
                    stderr.write(f'Failed to open file: {filename}\n')
                    continue
                decoder.play(CHUNK_LEN, QUEUE_SIZE, src)
                print(f'Playing {filename} ({decoder.sample_type},',
                      f'{decoder.channel_config}, {decoder.frequency} Hz)')
                while src.playing:
                    print(
                        f' {pretty_time(src.offset_seconds)} /'
                        f' {pretty_time(decoder.length_seconds)}',
                        end='\r',
                        flush=True)
                    sleep(PERIOD)
                    ctx.update()
                print()
Ejemplo n.º 3
0
def test_cache_and_free(aiff, flac, ogg):
    """Test cache and free, with and without a current context."""
    with Device() as device, Context(device):
        cache([aiff, flac, ogg])
        free([aiff, flac, ogg])
    with raises(RuntimeError): cache([aiff, flac, ogg])
    with raises(RuntimeError): free([aiff, flac, ogg])
Ejemplo n.º 4
0
def test_source_stopped(wav):
    """Test the handling of source stopped message."""
    with Device() as device, Context(device) as context, Buffer(wav) as buffer:
        context.message_handler = mock('source_stopped')
        with buffer.play() as source:
            while source.playing:
                pass
            context.update()
            context.message_handler.source_stopped.assert_called_with(source)
Ejemplo n.º 5
0
def play(device: str, waveform: str, duration: float,
         frequency: float) -> None:
    """Play waveform at the given frequency for given duration."""
    with Device(device) as dev, Context(dev):
        print('Opened', dev.name)
        dec = ToneGenerator(waveform, duration, frequency)
        print(f'Playing {waveform} signal at {frequency} Hz for {duration} s')
        with Buffer.from_decoder(dec, 'tonegen') as buf, buf.play():
            sleep(duration)
Ejemplo n.º 6
0
def test_buffer_loading(aiff):
    """Test the handling of buffer loading message."""
    with Device() as device, Context(device) as context:
        context.message_handler = mock('buffer_loading')
        with Buffer(aiff), aifc.open(aiff, 'r') as f:
            args, kwargs = context.message_handler.buffer_loading.call_args
            name, channel_config, sample_type, sample_rate, data = args
            assert name == aiff
            assert channel_config == channel_configs[f.getnchannels() - 1]
            assert sample_type == sample_types[f.getsampwidth() - 1]
            assert sample_rate == f.getframerate()
Ejemplo n.º 7
0
def test_resource_not_found(flac):
    """Test the handling of resource not found message."""
    with Device() as device, Context(device) as context:
        context.message_handler = mock('resource_not_found')
        context.message_handler.resource_not_found.return_value = ''
        name = str(uuid4())
        try:
            decode(name)
        except RuntimeError:
            pass
        context.message_handler.resource_not_found.assert_called_with(name)
Ejemplo n.º 8
0
def test_source_force_stopped(ogg):
    """Test the handling of source force stopped message."""
    with Device() as device, Context(device) as context:
        context.message_handler = mock('source_force_stopped')
        # TODO: test source preempted by a higher-prioritized one
        with Buffer(ogg) as buffer:
            source = buffer.play()
        context.message_handler.source_force_stopped.assert_called_with(source)
        with SourceGroup() as group, Buffer(ogg) as buffer:
            source.group = group
            buffer.play(source)
            group.stop_all()
        context.message_handler.source_force_stopped.assert_called_with(source)
        source.destroy()
Ejemplo n.º 9
0
def play(files: Iterable[str], device: str, hrtf_name: str,
         omega: float) -> None:
    """Render files using HRTF with source rotating in omega rad/s."""
    with Device(device) as dev:
        print('Opened', dev.name)
        hrtf_names = dev.hrtf_names
        if hrtf_names:
            print('Available HRTFs:')
            for name in hrtf_names:
                print(f'    {name}')
        else:
            print('No HRTF found!')
        attrs = {HRTF: TRUE}
        if hrtf_name is not None:
            try:
                attrs[HRTF_ID] = hrtf_names.index(hrtf_name)
            except ValueError:
                stderr.write(f'HRTF {hrtf_name!r} not found\n')

        with Context(dev, attrs) as ctx, Source() as src:
            if dev.hrtf_enabled:
                print(f'Using HRTF {dev.current_hrtf!r}')
            else:
                print('HRTF not enabled!')
            src.spatialize = True

            for filename in files:
                try:
                    decoder = decode(filename)
                except RuntimeError:
                    stderr.write(f'Failed to open file: {filename}\n')
                    continue
                decoder.play(CHUNK_LEN, QUEUE_SIZE, src)
                print(f'Playing {filename} ({decoder.sample_type},',
                      f'{decoder.channel_config}, {decoder.frequency} Hz)')

                for i in takewhile(lambda i: src.playing, count(step=PERIOD)):
                    print(
                        f' {pretty_time(src.offset_seconds)} /'
                        f' {pretty_time(decoder.length_seconds)}',
                        end='\r',
                        flush=True)
                    src.position = sin(i * omega), 0, -cos(i * omega)
                    sleep(PERIOD)
                    ctx.update()
                print()
Ejemplo n.º 10
0
def play(files: Iterable[str], device: str) -> None:
    """Load and play files on the given device."""
    with Device(device) as dev, Context(dev) as ctx:
        print('Opened', dev.name)
        ctx.message_handler = EventHandler()
        for filename in files:
            try:
                buffer = Buffer(filename)
            except RuntimeError:
                stderr.write(f'Failed to open file: {filename}\n')
                continue
            with buffer:
                src = buffer.play()
                while src.playing:
                    print(f' {pretty_time(src.offset_seconds)} /'
                          f' {pretty_time(buffer.length_seconds)}',
                          end='\r', flush=True)
                    sleep(PERIOD)
                print()
                ctx.update()
Ejemplo n.º 11
0
def play(files: Iterable[str], device: str) -> None:
    """Load and play files on the given device."""
    with Device(device) as dev, Context(dev):
        print('Opened', dev.name)
        for filename in files:
            try:
                buffer = Buffer(filename)
            except RuntimeError:
                stderr.write(f'Failed to open file: {filename}\n')
                continue
            with buffer, buffer.play() as src:
                print(f'Playing {filename} ({buffer.sample_type},',
                      f'{buffer.channel_config}, {buffer.frequency} Hz)')
                while src.playing:
                    print(
                        f' {pretty_time(src.offset_seconds)} /'
                        f' {pretty_time(buffer.length_seconds)}',
                        end='\r',
                        flush=True)
                    sleep(PERIOD)
                print()
Ejemplo n.º 12
0
def play(files: Iterable[str], device: str) -> None:
    """Load and play the file on given device."""
    with Device(device) as dev, Context(dev) as ctx, Source() as src:
        print('Opened', dev.name)
        for filename in files:
            try:
                decoder = decode(filename)
            except RuntimeError:
                stderr.write(f'Failed to open file: {filename}\n')
            decoder.play(CHUNK_LEN, QUEUE_SIZE, src)
            print(f'Playing {filename} ({decoder.sample_type},',
                  f'{decoder.channel_config}, {decoder.frequency} Hz)')
            while src.playing:
                print('Offset:',
                      round(src.offset_seconds),
                      's - Latency:',
                      src.latency // 10**6,
                      'ms',
                      end='\r',
                      flush=True)
                sleep(PERIOD)
                ctx.update()
            print()
Ejemplo n.º 13
0
def test_source_setter(data):
    """Test setters of a Source when its context is not current."""
    with Device() as device, Context(device), Source() as source:
        with raises(RuntimeError), Context(device):
            setattr(source, data, getattr(source, data))
Ejemplo n.º 14
0
def test_nested_context_manager():
    """Test if the context manager returns to the previous context."""
    with Device() as device, Context(device) as context:
        with Context(device): pass
        assert current_context() == context
Ejemplo n.º 15
0
def test_init_others(cls):
    """Test implication of context during object initialization."""
    with Device() as device, Context(device):
        with cls(): pass
    with raises(RuntimeError):
        with cls(): pass
Ejemplo n.º 16
0
def test_buffer_loading(mp3):
    """Test implication of context during buffer loading."""
    with Device() as device, Context(device):
        with Buffer(mp3): pass
    with raises(RuntimeError):
        with Buffer(mp3): pass
Ejemplo n.º 17
0
def device():
    """Provide the default device."""
    with Device() as dev:
        yield dev
Ejemplo n.º 18
0
def test_stream_loading(wav):
    """Test implication of context during stream loading."""
    with Device() as device, Context(device): decode(wav)
    with raises(RuntimeError): decode(wav)
Ejemplo n.º 19
0
def test_current_context():
    """Test the current context."""
    with Device() as device, Context(device) as context:
        assert current_context() == context
    assert current_context() is None