Exemple #1
0
def test_message_handler(device):
    """Test read-write property MessageHandler."""
    context = Context(device)
    assert type(context.message_handler) is MessageHandler
    message_handler_test = type('MessageHandlerTest', (MessageHandler, ), {})()
    context.message_handler = message_handler_test
    assert context.message_handler is message_handler_test
    with context:
        assert current_context().message_handler is context.message_handler
Exemple #2
0
def test_comparison(device):
    """Test basic comparisons."""
    with Context(device) as c0, Context(device) as c1, Context(device) as c2:
        assert c0 != c1
        contexts = [c1, c1, c0, c2]
        contexts.sort()
        contexts.remove(c2)
        contexts.remove(c0)
        assert contexts[0] == contexts[1]
Exemple #3
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
Exemple #4
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()
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])
Exemple #6
0
def test_default_resampler_index(device):
    """Test read-only property default_resampler_index."""
    with Context(device) as context:
        index = context.default_resampler_index
        assert index >= 0
        assert len(context.available_resamplers) > index
        with raises(AttributeError):
            context.available_resamplers = 0
Exemple #7
0
def test_format_support(device):
    """Test method is_supported."""
    with Context(device) as context:
        assert isinstance(context.is_supported('Rear', '32-bit float'), bool)
        with raises(ValueError):
            context.is_supported('Shu', 'Mulaw')
        with raises(ValueError):
            context.is_supported('Stereo', 'Type')
Exemple #8
0
def test_distance_model(device):
    """Test write-only distance_model."""
    with Context(device) as context:
        for model in distance_models:
            context.distance_model = model
        with raises(ValueError):
            context.distance_model = 'EYYYYLMAO'
        with raises(AttributeError):
            context.distance_model
Exemple #9
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)
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)
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()
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)
Exemple #13
0
def test_doppler_factor(device):
    """Test write-only property doppler_factor."""
    with Context(device) as context:
        context.doppler_factor = 4 / 9
        context.doppler_factor = 9 / 4
        context.doppler_factor = 0
        context.doppler_factor = inf
        with raises(ValueError):
            context.doppler_factor = -1
        with raises(AttributeError):
            context.doppler_factor
Exemple #14
0
def test_speed_of_sound(device):
    """Test write-only property speed_of_sound."""
    with Context(device) as context:
        context.speed_of_sound = 5 / 7
        context.speed_of_sound = 7 / 5
        with raises(ValueError):
            context.speed_of_sound = 0
        context.speed_of_sound = inf
        with raises(ValueError):
            context.speed_of_sound = -1
        with raises(AttributeError):
            context.speed_of_sound
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()
Exemple #16
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()
Exemple #17
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()
Exemple #18
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()
Exemple #19
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()
Exemple #20
0
                    nargs='?',
                    help='name of device to give extra info')
args = parser.parse_args()

with args.device:
    print('Available basic devices, with the first being default:',
          *device_names.basic,
          sep='\n  ')
    print('\nAvailable devices, with the first being default:',
          *device_names.full,
          sep='\n  ')
    print('\nAvailable capture devices, with the first being default:',
          *device_names.capture,
          sep='\n  ')

    print(f'\nInfo of device {args.device.name!r}:')
    print('ALC version: {}.{}'.format(*args.device.alc_version))

    with Context(args.device) as ctx:
        default_idx = ctx.default_resampler_index
        resamplers = ctx.available_resamplers
        resamplers[default_idx] += ' (default)'
        print('Available resamplers:', *resamplers, sep='\n  ')

    efx = args.device.efx_version
    if efx == (0, 0):
        print('EFX not supported!')
    else:
        print('EFX version: {}.{}'.format(*efx))
        print('Max auxiliary sends:', args.device.max_auxiliary_sends)
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))
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
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
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
Exemple #25
0
def context(device):
    """Provide a context creared from the default device
    (default context).
    """
    with Context(device) as ctx:
        yield ctx
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)
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
Exemple #28
0
def test_bool(device):
    """Test boolean value."""
    with Context(device) as context:
        assert context
    assert not context
Exemple #29
0
def test_batch_control(device):
    """Test calls of start_batch and end_batch."""
    with Context(device) as context:
        # At the moment these are no-op.
        context.start_batch()
        context.end_batch()
Exemple #30
0
def test_async_wake_interval(device):
    """Test read-write property async_wake_interval."""
    with Context(device) as context:
        context.async_wake_interval = 42
        assert context.async_wake_interval == 42