コード例 #1
0
async def test(filenames: list, queue):
    """ Try playing in a coroutine.

    """

    import musio

    for filename in filenames:
        with musio.open_file(filename, blacklist=['text'], loops=0) as music:
            print(music)
            dev = musio.open_device(music)
            paused = False
            while True:
                if not paused:
                    if dev.closed:
                        dev = musio.open_device(music)

                    buf = music.readline()
                    if not buf: break
                    buf += type(buf)(max(0, dev.buffer_size - len(buf)))
                    dev.write(buf)

                    if music.length > 0:
                        # Calculate the percentage played.
                        pos = (music.position * 100) / music.length

                        # Make the string.
                        pos_str = 'Position: %.2f%%' % pos

                        # Find the length of the string.
                        format_len = len(pos_str) + 2

                        print('\033[%dD\033[K%s' % (format_len, pos_str),
                              end='',
                              flush=True)
                else:
                    if not dev.closed:
                        dev.close()

                await asyncio.sleep(0.001)

                if not queue.empty():
                    data = await queue.get()
                    if data == 'Quit':
                        await queue.put('Done.')
                        return
                    elif data.startswith('C'):
                        break
                    elif data.startswith('P'):
                        paused = not paused
                    elif data.startswith('F'):
                        music.position += ((music.length // 100) * 2)
                    elif data.startswith('B'):
                        music.position -= ((music.length // 100) * 2)

    await queue.put('Done.')
コード例 #2
0
def pipe_out(filename_list: list) -> int:
    """Read from the specified file and write to stdout."""
    if filename_list:
        from musio import open_file

        # Loop throuth all the filenames supplied.
        for filename in filename_list:
            # Don't loop over one file.
            with open_file(filename, loops=0) as infile:
                # Loop until the end of the file.
                for data in infile:
                    stdout.buffer.write(data)

    return 0
コード例 #3
0
ファイル: musiopipe.py プロジェクト: zepto/musio-python2
def pipe_out(filename_list):
    """ Read from the specified file and write to stdout.

    """

    if filename_list:
        from musio import open_file

        # Loop throuth all the filenames supplied.
        for filename in filename_list:
            # Don't loop over one file.
            with open_file(filename, loops=0) as infile:
                # Loop until the end of the file.
                for data in infile:
                    sys_stdout.write(data)

    return 0
コード例 #4
0
ファイル: musioencode.py プロジェクト: zepto/musio
def main(args: dict) -> None:
    """ Encode args['filename'] times.

    """

    from os.path import basename as os_basename
    from os.path import isfile as os_isfile
    from os.path import splitext as os_splitext
    from sys import stdin as sys_stdin
    from select import select
    from time import sleep as time_sleep
    from termios import tcgetattr, tcsetattr, ECHO, ICANON, TCSANOW
    from termios import VMIN, VTIME

    from musio import open_file, open_device

    if args['debug']:
        from musio import io_util
        io_util.DEBUG = True

    filename = args['filename']
    output = os_splitext(os_basename(filename))[0] + '.' + args['filetype']
    output_bytes = output.encode('utf-8', 'surrogateescape')
    output_printable = output_bytes.decode('utf-8', 'ignore')
    if os_isfile(output):
        if input("Overwrite %s (y/n): " % output_printable).lower().startswith('n'):
            return

    # Save the current terminal state.
    normal = tcgetattr(sys_stdin)
    quiet = tcgetattr(sys_stdin)

    # Do not wait for key press and don't echo.
    quiet[3] &= ~(ECHO | ICANON)
    quiet[6][VMIN] = 0
    quiet[6][VTIME] = 0

    # Set the new terminal state.
    tcsetattr(sys_stdin, TCSANOW, quiet)

    # Value returned to tell the calling function whether to quit or
    # not.
    quit_val = True

    if args['filetype'].lower() == 'ogg':
        quality = args['quality'] / 10 if args['quality'] in range(-1, 11) else 0.5
    elif args['filetype'].lower() == 'mp3':
        quality = args['quality'] if args['quality'] in range(0, 10) else 2

    try:
        with open_file(**args) as in_file:
            in_file_title = in_file._info_dict.get('title',
                                                in_file._info_dict['name'])
            comment_dict = {'title': in_file_title}
            comment_dict.update(in_file._info_dict)
            for i in ['title', 'artist', 'album', 'year', 'comment',
                      'track', 'genre']:
                if args.get(i, ''):
                    comment_dict[i] = args[i]

            with open_file(output, 'w', depth=in_file.depth, rate=in_file.rate,
                        channels=in_file.channels, quality=quality,
                        comment_dict=comment_dict) as out_file:
                in_file.loops = 0

                if args['show_position']:
                    filename_bytes = filename.encode('utf-8', 'surrogateescape')
                    filename_printable = filename_bytes.decode('utf-8', 'ignore')
                    print("Encoding: %s to %s" % (filename_printable, output_printable))
                    print(in_file)

                for data in in_file:
                    if args['show_position']:
                        if in_file.length > 0:
                            # Calculate the percentage played.
                            pos = (in_file.position * 100) / in_file.length

                            # Make the string.
                            pos_str = 'Position: %.2f%%' % pos

                            # Find the length of the string.
                            format_len = len(pos_str) + 2

                            # Print the string and after erasing the old
                            # one using ansi escapes.
                            print('\033[%dD\033[K%s' % (format_len, pos_str),
                                  end='', flush=True)
                    out_file.write(data)

                    # Check for input.
                    r, _, _ = select([sys_stdin], [], [], 0)

                    # Get input if there was any otherwise continue.
                    if r:
                        command = r[0].readline().lower()
                        # Handle input commands.
                        if command.startswith('q'):
                            quit_val = False
                            break
                        elif command == '\n':
                            break

    except Exception as err:
        print("Error: %s" % err, flush=True)
        raise(err)
    finally:
        # Re-set the terminal state.
        tcsetattr(sys_stdin, TCSANOW, normal)

    if args['show_position']:
        print("\nDone.")

    return quit_val
コード例 #5
0
    def _main_loop(self, pipe):
        """ The main loop.

        """

        mus_file = mus_dev = None

        playing = False
        while True:
            if mus_file and playing:
                buf = mus_file.readline()
                if not buf:
                    mus_file.close()
                    mus_dev.close()
                    mus_file = mus_dev = None
                    playing = False
                    continue
                mus_dev.write(buf)
            else:
                time.sleep(0.05)

            if pipe.poll():
                signal, data = pipe.recv()
            else:
                continue

            if signal == 'open':
                if mus_file: mus_file.close()
                if mus_dev: mus_dev.close()
                mus_file = open_file(
                    data, soundfont='/usr/share/soundfonts/FluidR3_GM2-2.sf2')
                mus_dev = open_device(mus_file)
                pipe.send(('open', True))
            if signal == 'play':
                if mus_file:
                    if mus_dev.closed: mus_dev = open_device(mus_file)
                    playing = True
                pipe.send(('playing', playing))
            if signal == 'pause' and playing:
                playing = False
                if not mus_dev.closed:
                    mus_dev.close()
                pipe.send(('playing', playing))
            if signal == 'stop':
                playing = False
                if mus_file:
                    mus_file.seek(0)
                if not mus_dev.closed:
                    mus_dev.close()
                pipe.send(('playing', playing))
            if signal == 'quit':
                break

            if signal == 'is-playing':
                pipe.send(('playing', playing))
            if signal == 'is-open':
                pipe.send(('open', not mus_file.closed if mus_file else False))

            if signal == 'set-position':
                if mus_file: mus_file.position = data
            if signal == 'set-loops':
                if mus_file: mus_file.loops = data

            if signal == 'get-position':
                pipe.send(('position', mus_file.position if mus_file else 0))
            if signal == 'get-length':
                pipe.send(('length', mus_file.length if mus_file else 0))
            if signal == 'get-loops':
                pipe.send(('loops', mus_file.loops if mus_file else -1))
            if signal == 'get-str':
                pipe.send(('str', str(mus_file)))

        if mus_file: mus_file.close()
        if mus_dev: mus_dev.close()
コード例 #6
0
def main(args):
    """ Encode args['filename'] times.

    """

    from os.path import basename as os_basename
    from os.path import isfile as os_isfile
    from os.path import splitext as os_splitext
    from sys import stdin as sys_stdin
    from sys import stdout as sys_stdout
    from select import select
    from time import sleep as time_sleep
    from termios import tcgetattr, tcsetattr, ECHO, ICANON, TCSANOW
    from termios import VMIN, VTIME

    from musio import open_file, open_device

    if args['debug']:
        from musio import io_util
        io_util.DEBUG = True

    filename = args['filename']
    output = os_splitext(os_basename(filename))[0] + '.' + args['filetype']
    output_bytes = output.encode('utf-8', 'surrogateescape')
    output_printable = output_bytes.decode('utf-8', 'ignore')
    if os_isfile(output):
        if raw_input("Overwrite %s (y/n): " % output_printable).lower().startswith('n'):
            return

    # Save the current terminal state.
    normal = tcgetattr(sys_stdin)
    quiet = tcgetattr(sys_stdin)

    # Do not wait for key press and don't echo.
    quiet[3] &= ~(ECHO | ICANON)
    quiet[6][VMIN] = 0
    quiet[6][VTIME] = 0

    # Set the new terminal state.
    tcsetattr(sys_stdin, TCSANOW, quiet)

    # Value returned to tell the calling function whether to quit or
    # not.
    quit_val = True

    if args['filetype'].lower() == 'ogg':
        quality = args['quality'] / 10 if args['quality'] in range(-1, 11) else 0.5
    elif args['filetype'].lower() == 'mp3':
        quality = args['quality'] if args['quality'] in range(0, 10) else 2

    try:
        with open_file(**args) as in_file:
            in_file_title = in_file._info_dict.get('title',
                                                in_file._info_dict['name'])
            comment_dict = {'title': in_file_title}
            comment_dict.update(in_file._info_dict)
            for i in ['title', 'artist', 'album', 'year', 'comment',
                      'track', 'genre']:
                if args.get(i, ''):
                    comment_dict[i] = args[i]

            with open_file(output, 'w', depth=in_file.depth, rate=in_file.rate,
                        channels=in_file.channels, quality=quality,
                        comment_dict=comment_dict) as out_file:
                in_file.loops = 0

                if args['show_position']:
                    filename_bytes = filename.encode('utf-8', 'surrogateescape')
                    filename_printable = filename_bytes.decode('utf-8', 'ignore')
                    print("Encoding: %s to %s" % (filename, output))
                    print(in_file)

                for data in in_file:
                    if args['show_position']:
                        if in_file.length > 0:
                            # Calculate the percentage played.
                            pos = (in_file.position * 100) / float(in_file.length)

                            # Make the string.
                            pos_str = 'Position: %.2f%%' % pos

                            # Find the length of the string.
                            format_len = len(pos_str) + 2

                            # Print the string and after erasing the old
                            # one using ansi escapes.
                            print('\033[%dD\033[K%s' % (format_len, pos_str),
                                  end='')
                            sys_stdout.flush()
                    out_file.write(data)

                    # Check for input.
                    r, _, _ = select([sys_stdin], [], [], 0)

                    # Get input if there was any otherwise continue.
                    if r:
                        command = r[0].readline().lower()
                        # Handle input commands.
                        if command.startswith('q'):
                            quit_val = False
                            break
                        elif command == '\n':
                            break

    except Exception as err:
        print("Error: %s" % err)
        raise(err)
    finally:
        # Re-set the terminal state.
        tcsetattr(sys_stdin, TCSANOW, normal)

    if args['show_position']:
        print("\nDone.")

    return quit_val
コード例 #7
0
def main(args: dict):
    """Play args['filename'] args['loops'] times."""
    import atexit
    import time
    from pathlib import Path
    from select import select
    from sys import stdin
    from termios import (ECHO, ICANON, TCSANOW, VMIN, VTIME, tcgetattr,
                         tcsetattr)

    from musio import open_file
    from musio.dummy_file import DummyFile
    from musio.io_util import get_codec
    from musio.player_util import get_files
    from musio.portaudio_io import Portaudio

    # Save the current terminal state.
    normal = tcgetattr(stdin)
    quiet = tcgetattr(stdin)

    # Do not wait for key press and don't echo.
    quiet[3] &= ~(ECHO | ICANON)
    quiet[6][VMIN] = 0
    quiet[6][VTIME] = 0

    # Set the new terminal state.
    tcsetattr(stdin, TCSANOW, quiet)

    # Re-set the terminal state.
    atexit.register(tcsetattr, stdin, TCSANOW, normal)

    quit_command = False

    # Pop the filenames list out of the args dict.
    filenames = args.pop('filename')

    # Recursively get all the files.
    recurse = args.pop('recurse')
    if recurse:
        filenames = get_files(filenames)

    for filename in filenames:
        if quit_command:
            break
        if not Path(filename).is_file():
            continue

        # Skip unsupported files.
        try:
            temp = get_codec(filename, blacklist=[*args['blacklist'], 'all'])
            if temp == DummyFile:
                raise (IOError(f"File {filename} not supported."))
        except Exception as err:
            print(err)
            continue

        command_dict = {'position': [], 'show_position': args['show_position']}
        with open_file(filename, blacklist=args['blacklist']) as audio_file:
            audio_file.loops = args['loops']
            if args['show_position']:
                print(f"\n{audio_file}")
            with Portaudio(mode="w",
                           rate=audio_file.rate,
                           channels=audio_file.channels,
                           device="default",
                           floatp=audio_file.floatp,
                           unsigned=audio_file.unsigned,
                           depth=audio_file.depth,
                           callback=callback,
                           callback_data=(audio_file, command_dict)) as device:
                # Loop until playing stops.
                while device.is_stream_active or device.is_stream_stopped:
                    # Check for input.
                    r, _, _ = select([stdin], [], [], 0)

                    # Get input if there was any otherwise continue.
                    if r:
                        command = r[0].readline().lower()
                    else:
                        try:
                            time.sleep(0.1)
                            continue
                        except KeyboardInterrupt:
                            break

                    # Handle input commands.
                    if command.startswith("p") or command.startswith(" "):
                        (device.stop_stream()
                         if device.is_stream_active else device.start_stream())
                    elif (command.startswith("l")
                          or command.endswith("\033[c")):
                        new_pos = audio_file.position + audio_file.length / 100
                        command_dict['position'].append(new_pos)
                    elif (command.startswith("h")
                          or command.endswith("\033[d")):
                        new_pos = audio_file.position - audio_file.length / 100
                        command_dict['position'].append(new_pos)
                    elif command == "\n" or command.startswith("q"):
                        quit_command = command.startswith("q")
                        break

                device.abort_stream()
                if args['show_position']:
                    print("\nDone.")
コード例 #8
0
def main(args: dict) -> bool:
    """Encode args['filename'] times."""
    from os.path import basename, isfile, splitext
    from select import select
    from sys import stdin
    from termios import (ECHO, ICANON, TCSANOW, VMIN, VTIME, tcgetattr,
                         tcsetattr)

    from musio import open_file

    if args['debug']:
        from musio import io_util
        io_util.DEBUG = True

    filename = args['filename']
    output = splitext(basename(filename))[0] + '.' + args['filetype']
    output_bytes = output.encode('utf-8', 'surrogateescape')
    output_printable = output_bytes.decode('utf-8', 'ignore')
    if isfile(output):
        overwrite = input(f"Overwrite {output_printable} (y/n): ").lower()
        if overwrite.startswith("n"):
            return False

    # Save the current terminal state.
    normal = tcgetattr(stdin)
    quiet = tcgetattr(stdin)

    # Do not wait for key press and don't echo.
    quiet[3] &= ~(ECHO | ICANON)
    quiet[6][VMIN] = 0
    quiet[6][VTIME] = 0

    # Set the new terminal state.
    tcsetattr(stdin, TCSANOW, quiet)

    # Value returned to tell the calling function whether to quit or
    # not.
    quit_val = True

    if args['filetype'].lower() == 'ogg':
        quality = args['quality'] / 10 if args['quality'] in range(-1,
                                                                   11) else 0.5
    elif args['filetype'].lower() == 'mp3':
        quality = args['quality'] if args['quality'] in range(0, 10) else 2
    else:
        quality = 5

    try:
        with open_file(blacklist=args['input_blacklist'], **args) as in_file:
            in_file_title = in_file._info_dict.get('title',
                                                   in_file._info_dict['name'])
            comment_dict = {'title': in_file_title}
            comment_dict.update(in_file._info_dict)
            for i in [
                    'title', 'artist', 'album', 'year', 'comment', 'track',
                    'genre'
            ]:
                if args.get(i, ''):
                    comment_dict[i] = args[i]

            with open_file(output,
                           'w',
                           depth=in_file.depth,
                           rate=in_file.rate,
                           channels=in_file.channels,
                           quality=quality,
                           floatp=in_file._floatp,
                           unsigned=in_file._unsigned,
                           comment_dict=comment_dict,
                           bit_rate=args['bit_rate'],
                           blacklist=args['output_blacklist']) as out_file:
                in_file.loops = 0
                if args['debug']:
                    print(repr(in_file))
                    print(repr(out_file))

                if args['show_position']:
                    filename_bytes = filename.encode('utf-8',
                                                     'surrogateescape')
                    filename_printable = filename_bytes.decode(
                        'utf-8', 'ignore')
                    print(f"Encoding: {filename_printable} to "
                          f"{output_printable}")
                    print(in_file)

                for data in in_file:
                    if args['show_position']:
                        if in_file.length > 0:
                            # Calculate the percentage played.
                            pos = (in_file.position * 100) / in_file.length

                            # Make the string.
                            pos_str = f"Position: {pos:.2f}%"

                            # Find the length of the string.
                            format_len = len(pos_str) + 2

                            # Print the string and after erasing the old
                            # one using ansi escapes.
                            print(f"\033[{format_len}D\033[K{pos_str}",
                                  end='',
                                  flush=True)
                    out_file.write(data)

                    # Check for input.
                    r, _, _ = select([stdin], [], [], 0)

                    # Get input if there was any otherwise continue.
                    if r:
                        command = r[0].readline().lower()
                        # Handle input commands.
                        if command.startswith('q'):
                            quit_val = False
                            break
                        elif command == '\n':
                            break

    except Exception as err:
        print("Error: %s" % err, flush=True)
        raise (err)
    finally:
        # Re-set the terminal state.
        tcsetattr(stdin, TCSANOW, normal)

    if args['show_position']:
        print("\nDone.")

    return quit_val