예제 #1
0
파일: play.py 프로젝트: irmen/pyminiaudio
def stream_file(info, filename):
    def progress_stream_wrapper(stream) -> miniaudio.PlaybackCallbackGeneratorType:
        framecount = yield(b"")
        try:
            while True:
                framecount = yield stream.send(framecount)
                print(".", end="", flush=True)
        except StopIteration:
            return

    output_format = info.sample_format
    try:
        filestream = miniaudio.stream_file(filename, output_format=output_format, sample_rate=info.sample_rate)
    except miniaudio.MiniaudioError as x:
        print("Cannot create optimal stream:", x)
        print("Creating stream with different sample format!")
        output_format = miniaudio.SampleFormat.SIGNED16
        filestream = miniaudio.stream_file(filename, output_format=output_format, sample_rate=info.sample_rate,
                                           dither=miniaudio.DitherMode.TRIANGLE)

    stream = progress_stream_wrapper(filestream)
    next(stream)   # start the generator
    with miniaudio.PlaybackDevice(output_format=output_format, sample_rate=info.sample_rate) as device:
        print("playback device backend:", device.backend, device.format.name, device.sample_rate, "hz")
        print("Audio file playing in the background. Enter to stop playback: ")
        device.start(stream)
        input()
예제 #2
0
    def play(self):

        stream = miniaudio.stream_file(self.file_path)
        with miniaudio.PlaybackDevice() as device:
            device.start(stream)
            input(
                "Audio file playing in the background. Enter to stop playback: "
            )
예제 #3
0
 def __init__(self):
     super().__init__()
     default_font = nametofont("TkDefaultFont")
     default_font.configure(size=12)
     self.wm_title("Python ModPlayer -- libxmplite v{} -- xmp v{}".format(libxmplite.__version__, libxmplite.xmp_version))
     self.load_button = tkinter.Button(self, text="Load module", command=self.load_module, bg="teal")
     self.load_button.pack(anchor=tkinter.W)
     # self.load_button = tkinter.Button(self, text="Pause/Unpause", command=self.pause)
     # self.load_button.pack()
     info_frame = tkinter.Frame(self, width=10)
     info_frame.title_label = tkinter.Label(info_frame, text="title")
     info_frame.title_label.grid(row=0, column=0, padx=10, sticky=tkinter.E)
     info_frame.type_label = tkinter.Label(info_frame, text="type")
     info_frame.type_label.grid(row=1, column=0, padx=10, sticky=tkinter.E)
     info_frame.channels_label = tkinter.Label(info_frame, text="channels")
     info_frame.channels_label.grid(row=2, column=0, padx=10, sticky=tkinter.E)
     info_frame.bpm_label = tkinter.Label(info_frame, text="bpm")
     info_frame.bpm_label.grid(row=3, column=0, padx=10, sticky=tkinter.E)
     info_frame.time_label = tkinter.Label(info_frame, text="time")
     info_frame.time_label.grid(row=5, column=0, padx=10, sticky=tkinter.E)
     info_frame.pos_label = tkinter.Label(info_frame, text="pos")
     info_frame.pos_label.grid(row=6, column=0, padx=10, sticky=tkinter.E)
     info_frame.pat_label = tkinter.Label(info_frame, text="pat")
     info_frame.pat_label.grid(row=7, column=0, padx=10, sticky=tkinter.E)
     info_frame.row_label = tkinter.Label(info_frame, text="row")
     info_frame.row_label.grid(row=8, column=0, padx=10, sticky=tkinter.E)
     info_frame.title_e = tkinter.Label(info_frame, relief=tkinter.SUNKEN)
     info_frame.title_e.grid(row=0, column=1, sticky=tkinter.W)
     info_frame.type_e = tkinter.Label(info_frame, relief=tkinter.SUNKEN)
     info_frame.type_e.grid(row=1, column=1, sticky=tkinter.W)
     info_frame.channels_e = tkinter.Label(info_frame, relief=tkinter.SUNKEN)
     info_frame.channels_e.grid(row=2, column=1, sticky=tkinter.W)
     info_frame.bpm_e = tkinter.Label(info_frame, relief=tkinter.SUNKEN)
     info_frame.bpm_e.grid(row=3, column=1, sticky=tkinter.W)
     info_frame.time_e = tkinter.Label(info_frame, relief=tkinter.SUNKEN)
     info_frame.time_e.grid(row=5, column=1, sticky=tkinter.W)
     info_frame.pos_e = tkinter.Label(info_frame, relief=tkinter.SUNKEN)
     info_frame.pos_e.grid(row=6, column=1, sticky=tkinter.W)
     info_frame.pat_e = tkinter.Label(info_frame, relief=tkinter.SUNKEN)
     info_frame.pat_e.grid(row=7, column=1, sticky=tkinter.W)
     info_frame.row_e = tkinter.Label(info_frame, relief=tkinter.SUNKEN)
     info_frame.row_e.grid(row=8, column=1, sticky=tkinter.W)
     self.info_frame = info_frame
     self.info_frame.columnconfigure(1, minsize=200)
     self.info_frame.rowconfigure(4, minsize=20)
     self.info_frame.pack(side=tkinter.LEFT, padx=10, fill=tkinter.X, expand=tkinter.YES)
     tracks_holder = tkinter.Frame(relief=tkinter.RIDGE, height=256, width=200)
     self.tracks_holder = tracks_holder
     self.tracks_holder.pack(fill=tkinter.X, expand=tkinter.YES, padx=16, pady=16)
     # pbstyle = tkinter.ttk.Style()
     # pbstyle.theme_use("classic")
     self.audiodevice = miniaudio.PlaybackDevice(output_format=miniaudio.SampleFormat.SIGNED16, nchannels=2, sample_rate=44100)
     self.xmp = libxmplite.Xmp()
     self.tracks = []
     self.playing = False
     self.previous_update_time = 0
예제 #4
0
def play(song_name):
    """Function used for playing audio from Storage folder"""

    import miniaudio
    stream = miniaudio.stream_file('Storage/' + song_name)
    with miniaudio.PlaybackDevice() as device:
        device.start(stream)
        input("Audio file playing in the background. Enter to stop playback: ")

    pass
예제 #5
0
    def _start_device(self):
        with miniaudio.PlaybackDevice(
            output_format=miniaudio.SampleFormat.SIGNED16,
            backends=[miniaudio.Backend.PULSEAUDIO],
            nchannels=CHANNELS,
            sample_rate=SAMPLE_RATE) as device:

            generator = self._read_frames()
            next(generator)
            device.start(generator)
            self.running.acquire()  # keep the thread running or else audio stops
예제 #6
0
 def __init__(self, samplerate: int = 0, samplewidth: int = 0, nchannels: int = 0, queue_size: int = 100) -> None:
     super().__init__(samplerate, samplewidth, nchannels, queue_size=queue_size)
     self.command_queue = queue.Queue(maxsize=queue_size)        # type: queue.Queue[Dict[str, Any]]
     output_format = {
         1: miniaudio.SampleFormat.UNSIGNED8,
         2: miniaudio.SampleFormat.SIGNED16,
         3: miniaudio.SampleFormat.SIGNED24,
         4: miniaudio.SampleFormat.SIGNED32
     }[self.samplewidth]
     self.device = miniaudio.PlaybackDevice(output_format, self.nchannels, self.samplerate)
     stream = self.generator()
     next(stream)  # start generator
     self.device.start(stream)
예제 #7
0
def test_stop_callback_playback(backends, jackd_server):
    stop_callback = mock.Mock()

    playback = miniaudio.PlaybackDevice(backends=backends)
    gen = dummy_generator()
    next(gen)
    playback.start(gen, stop_callback)

    assert playback.running is True
    # Simulate an unexpected stop.
    miniaudio.lib.ma_device_stop(playback._device)

    stop_callback.assert_called_once()
    assert playback.running is False
예제 #8
0
 def __init__(self, samplerate: int = 0, samplewidth: int = 0, nchannels: int = 0, frames_per_chunk: int = 0) -> None:
     super().__init__(samplerate, samplewidth, nchannels, frames_per_chunk, 0)
     self.mixed_chunks = self.mixer.chunks()
     output_format = {
         1: miniaudio.SampleFormat.UNSIGNED8,
         2: miniaudio.SampleFormat.SIGNED16,
         3: miniaudio.SampleFormat.SIGNED24,
         4: miniaudio.SampleFormat.SIGNED32
     }[self.samplewidth]
     buffersize_msec = self.nchannels * 1000 * self.frames_per_chunk // self.samplerate
     self.mixed_chunks = self.mixer.chunks()
     self.device = miniaudio.PlaybackDevice(output_format, self.nchannels, self.samplerate, buffersize_msec)
     stream = self.generator()
     next(stream)  # start generator
     self.device.start(stream)
예제 #9
0
    def unpause(self):
        if self._played:
            return

        if not self._paused or self._device is None:
            raise RuntimeError("Cannot unpause invalid playback")

        self._device = miniaudio.PlaybackDevice(
            output_format=miniaudio.SampleFormat.SIGNED16,
            nchannels=self._channels,
            sample_rate=self._sample_rate)

        self._device.start(self._stream)
        self._played = True
        self._paused = False
예제 #10
0
    def play(self):
        if self._played:
            raise RuntimeError("Cannot be played again")

        if not self._paused:
            self._device = miniaudio.PlaybackDevice(
                output_format=miniaudio.SampleFormat.SIGNED16,
                nchannels=self._channels,
                sample_rate=self._sample_rate)

            self._stream = self.__sound_callback()
            next(self._stream)

        self._device.start(self._stream)
        self._played = True
        self._paused = False
예제 #11
0
def run_radio(q):
    def title_printer(client: miniaudio.IceCastClient, new_title: str) -> None:
        print("Stream title: ", new_title)

    with miniaudio.IceCastClient("http://23.237.150.178:9002",
                                 update_stream_title=title_printer) as source:

        #print("Connected to internet stream, audio format:", source.audio_format.name)
        #print("Station name: ", source.station_name)
        #print("Station genre: ", source.station_genre)
        #print("Press <enter> to quit playing.\n")
        stream = miniaudio.stream_any(source, source.audio_format)
        with miniaudio.PlaybackDevice() as device:
            device.start(stream)
            something = q.get()
            print(something)
예제 #12
0
def stream_file(info, filename):
    if info.file_format == miniaudio.FileFormat.FLAC:
        fstream = miniaudio.flac_stream_file(filename)
    elif info.file_format == miniaudio.FileFormat.MP3:
        fstream = miniaudio.mp3_stream_file(filename)
    elif info.file_format == miniaudio.FileFormat.VORBIS:
        fstream = miniaudio.vorbis_stream_file(filename)
    elif info.file_format == miniaudio.FileFormat.WAV:
        fstream = miniaudio.wav_stream_file(filename)
    else:
        raise IOError("unsupported audio file format")

    stream = playback_stream(fstream, info.nchannels)
    next(stream)  # start the generator
    with miniaudio.PlaybackDevice(output_format=info.sample_format, sample_rate=info.sample_rate, nchannels=info.nchannels) as play:
        play.start(stream)
        input("Audio file playing in the background. Enter to stop playback: ")
예제 #13
0
def stream_file(filename):
    def progress_stream_wrapper(stream) -> miniaudio.AudioProducerType:
        framecount = yield(b"")
        try:
            while True:
                framecount = yield stream.send(framecount)
                print(".", end="", flush=True)
        except StopIteration:
            return

    stream = progress_stream_wrapper(miniaudio.stream_file(filename))
    next(stream)   # start the generator
    device = miniaudio.PlaybackDevice()
    print("playback device backend:", device.backend)
    device.start(stream)
    input("Audio file playing in the background. Enter to stop playback: ")
    device.close()
예제 #14
0
    def play(self) -> bool:
        try:
            media = requests.get(self.stream, stream=True).raw
        except requests.exceptions.MissingSchema:
            return False

        channels: int = 2
        sample_rate: int = 44100
        device = miniaudio.PlaybackDevice()

        stream = miniaudio.stream_any(
            source=media,
            source_format=miniaudio.FileFormat.MP3,
            nchannels=channels,
            sample_rate=sample_rate,
        )

        device.start(stream)
        time.sleep(self.duration)
        device.close()
        return True
예제 #15
0
 def __init__(self, awsHelper, cache):
     self._awsHelper = awsHelper
     self._device = miniaudio.PlaybackDevice()
예제 #16
0
"""
Listing and Choosing the audio device to play on.
"""

import os
import miniaudio


def samples_path(filename):
    return os.path.join(os.path.abspath(os.path.dirname(__file__)), 'samples', filename)


def choose_device():
    devices = miniaudio.Devices()
    print("Available playback devices:")
    playbacks = devices.get_playbacks()
    for d in enumerate(playbacks, 1):
        print("{num} = {name}".format(num=d[0], name=d[1]['name']))
    choice = int(input("play on which device? "))
    return playbacks[choice-1]


if __name__ == "__main__":
    selected_device = choose_device()
    stream = miniaudio.stream_file(samples_path("music.mp3"))
    device = miniaudio.PlaybackDevice(device_id=selected_device["id"])
    device.start(stream)
    input("Audio file playing in the background. Enter to stop playback: ")
예제 #17
0
 def notificacion(self):
     stream = miniaudio.stream_file("notify.mp3")
     device = miniaudio.PlaybackDevice()
     device.start(stream)
     sleep(2)
     device.close()
예제 #18
0
 def playAudioInBackground(self):
     stream = miniaudio.stream_file("output.wav")
     with miniaudio.PlaybackDevice() as device:
         device.start(stream)
         input("Audio file playing in the background. Enter to stop playback: ")
예제 #19
0
파일: sound.py 프로젝트: rvanlaar/mrcrowbar
def play_pcm(source,
             channels,
             sample_rate,
             format_type,
             field_size,
             signedness,
             endian,
             start=None,
             end=None,
             length=None,
             interpolation=AudioInterpolation.LINEAR):
    """Play back a byte string as PCM audio.

    source
        The byte string to play.

    channels
        Number of audio channels.

    sample_rate
        Audio sample rate in Hz.

    format_type
        Type of sample encoding; either int or float.

    field_size
        Size of each sample, in bytes.

    signedness
        Signedness of each sample; either 'signed' or 'unsigned'.

    endian
        Endianness of each sample; either 'big', 'little' or None.

    start
        Start offset to read from (default: start).

    end
        End offset to stop reading at (default: end).

    length
        Length to read in (optional replacement for end).

    interpolation
        Interpolation algorithm to use for upsampling. Defaults to AudioInterpolation.LINEAR.
    """
    assert is_bytes(source)
    start, end = bounds(start, end, length, len(source))

    if not miniaudio:
        raise ImportError(
            'miniaudio must be installed for audio playback support (see https://github.com/irmen/pyminiaudio)'
        )

    format = getattr(miniaudio.SampleFormat, MINIAUDIO_NORMALISE_TYPE)
    playback_rate = None

    INTERP_MAP = {
        AudioInterpolation.NONE: miniaudio.DitherMode.NONE,
        AudioInterpolation.LINEAR: miniaudio.DitherMode.TRIANGLE,
        AudioInterpolation.STEP: miniaudio.DitherMode.RECTANGLE,
    }
    interpolation = INTERP_MAP.get(interpolation, miniaudio.DitherMode.NONE)
    FORMAT_MAP = {
        (int, 1, 'unsigned', None): miniaudio.SampleFormat.UNSIGNED8,
        (int, 2, 'signed', 'little'): miniaudio.SampleFormat.SIGNED16,
        (int, 3, 'signed', 'little'): miniaudio.SampleFormat.SIGNED24,
        (int, 4, 'signed', 'little'): miniaudio.SampleFormat.SIGNED32,
        (float, 4, 'signed', 'little'): miniaudio.SampleFormat.FLOAT32,
    }
    format = FORMAT_MAP.get((format_type, field_size, signedness, endian))
    if not format:
        raise ValueError('Format not supported yet!')

    with miniaudio.PlaybackDevice(output_format=format,
                                  nchannels=channels,
                                  sample_rate=PLAYBACK_RATE) as device:

        def audio_iter():
            conv = miniaudio.convert_frames(format, channels, sample_rate,
                                            source[start:end], device.format,
                                            device.nchannels,
                                            device.sample_rate)
            samp_iter = iter(conv)
            required_frames = yield b''
            old_time = time.time()
            while True:
                sample_data = bytes(
                    itertools.islice(samp_iter,
                                     required_frames * channels * field_size))
                if not sample_data:
                    break
                new_time = time.time()
                old_time = new_time
                required_frames = yield sample_data

        ai = audio_iter()
        next(ai)
        device.start(ai)
        while device.callback_generator:
            time.sleep(0.1)
예제 #20
0
    required_frames = yield b""  # generator initialization
    try:
        while True:
            buffer = xmp.play_buffer(required_frames * 2 * 2)
            display.update(xmp.frame_info())
            required_frames = yield buffer
    except libxmplite.XmpError as x:
        print("XMP Playback error!!", x)


if __name__ == "__main__":
    if len(sys.argv) != 2:
        raise SystemExit("must give mod filename to play as argument")

    device = miniaudio.PlaybackDevice(
        output_format=miniaudio.SampleFormat.SIGNED16,
        nchannels=2,
        sample_rate=44100)

    xmp = libxmplite.Xmp()
    xmp.load(sys.argv[1])
    xmp.start(device.sample_rate)

    mod_info = xmp.module_info()
    display = Display(mod_info)
    stream = stream_module(xmp, display)
    next(stream)  # start the generator
    device.start(stream)

    print("\nFile playing in the background. Press enter to stop playback!\n")
    input()
예제 #21
0
"""
Simplest example of decoding and playing an audio file
"""

import os
import miniaudio


def samples_path(filename):
    return os.path.join(os.path.abspath(os.path.dirname(__file__)), 'samples',
                        filename)


stream = miniaudio.stream_file(samples_path("music.mp3"),
                               dither=miniaudio.DitherMode.TRIANGLE)
device = miniaudio.PlaybackDevice()
device.start(stream)
input("Audio file playing in the background. Enter to stop playback: ")
device.close()
예제 #22
0
channels = 2
sample_rate = 48000
sample_width = 4  # 32bit float


def stream_pcm(source):
    required_frames = yield b""  # generator initialization
    while True:
        required_bytes = required_frames * channels * sample_width
        sample_data = source.read(required_bytes)
        if not sample_data:
            break
        # print(".", end="", flush=True)
        required_frames = yield sample_data


with miniaudio.PlaybackDevice(output_format=miniaudio.SampleFormat.FLOAT32,
                              nchannels=channels,
                              sample_rate=sample_rate) as device:
    fmradion = subprocess.Popen([
        "airspy-fmradion", "-E100", "-b0.001", "-t", "airspyhf", "-c",
        "freq=" + str(freq), "-F", "-"
    ],
                                stdin=None,
                                stdout=subprocess.PIPE)
    stream = stream_pcm(fmradion.stdout)
    next(stream)
    device.start(stream)
    input("Enter to stop playback\n")
    fmradion.terminate()
예제 #23
0
def son_chrono():
    stream = miniaudio.stream_file("buzzer1.mp3")
    device = miniaudio.PlaybackDevice()
    device.start(stream)
    input("\n Appuyer sur Enter pour passer à la suite du programme :")
    device.close()
예제 #24
0
파일: demo1.py 프로젝트: irmen/pyminiaudio
"""
Simplest example of decoding and playing an audio file
"""

import os
import miniaudio


def samples_path(filename):
    return os.path.join(os.path.abspath(os.path.dirname(__file__)), 'samples',
                        filename)


stream = miniaudio.stream_file(samples_path("music.mp3"),
                               dither=miniaudio.DitherMode.TRIANGLE)
with miniaudio.PlaybackDevice() as device:
    device.start(stream)
    input("Audio file playing in the background. Enter to stop playback: ")
예제 #25
0
def fbi_ACDC():
    stream = miniaudio.stream_file("Thunderstruck.mp3")
    device = miniaudio.PlaybackDevice()
    device.start(stream)
    input("\n Appuyer sur Enter pour terminer l'exercice :")
    device.close()
예제 #26
0
def main(config: str, make_config: bool) -> None:
    """
    This is a module which implements realtime polyphonic FM synthesis in Python
    controllable by MIDI. Note that this is very CPU-intensive.

    It's got the following features:

    - configurable polyphony;

    - AD envelope (no sustain yet);

    - dispatches MIDI IN events like NOTE_ON and NOTE_OFF events to the synthesizer.

    To use this yourself, you will need:

    - a MIDI IN port, can be virtual (I'm using IAC in Audio MIDI Setup on macOS);

    - an AUDIO OUT, can be virtual (I'm using BlackHole on macOS);

    - a DAW project which will be configured as follows (Renoise as an example):

        - a MIDI Instrument in the DAW configured to output notes to the MIDI port that
          fmsynth listens on (I call my virtual MIDI port "IAC fmsynth");

        - a #Line Input routing in the DAW configured to catch audio from the out that
          fmsynth (like "BlackHole 16ch 1+2");

        - turn on "MIDI Return Mode" to compensate latency;

        - in Ableton Live use "External Instrument" to do this in one place and
          automatically compensate latency.

    You can customize the ports by creating a config file.  Use `--make-config` to
    output a new config to stdout.

    Then run `python -m aiotone.fmsynth --config=PATH_TO_YOUR_CONFIG_FILE`.
    """
    if make_config:
        with open(CURRENT_DIR / "aiotone-fmsynth.ini") as f:
            print(f.read())
        return

    cfg = configparser.ConfigParser()
    cfg.read(config)

    devices = miniaudio.Devices()
    playbacks = devices.get_playbacks()
    audio_out = cfg["audio-out"]["out-name"]
    sample_rate = cfg["audio-out"].getint("sample-rate")
    buffer_msec = cfg["audio-out"].getint("buffer-msec")
    polyphony = cfg["audio-out"].getint("polyphony")
    for playback in playbacks:
        if playback["name"] == audio_out:
            play_id = playback["id"]
            break
    else:
        raise click.UsageError(f"No audio out available called {audio_out}")

    with miniaudio.PlaybackDevice(
        device_id=play_id,
        nchannels=2,
        sample_rate=sample_rate,
        output_format=miniaudio.SampleFormat.SIGNED16,
        buffersize_msec=buffer_msec,
    ) as dev:
        synth = Synthesizer(sample_rate=sample_rate, polyphony=polyphony)
        stream = synth.stereo_out()
        init(stream)
        dev.start(stream)
        try:
            asyncio.run(async_main(synth, cfg["midi-in"]))
        except KeyboardInterrupt:
            pass
예제 #27
0
filename = "samples/music.m4a"  # AAC encoded audio file


def stream_pcm(source):
    required_frames = yield b""  # generator initialization
    while True:
        required_bytes = required_frames * channels * sample_width
        sample_data = source.read(required_bytes)
        if not sample_data:
            break
        print(".", end="", flush=True)
        required_frames = yield sample_data


device = miniaudio.PlaybackDevice(ma_output_format=miniaudio.ma_format_s16,
                                  nchannels=channels,
                                  sample_rate=sample_rate)
ffmpeg = subprocess.Popen([
    "ffmpeg", "-v", "fatal", "-hide_banner", "-nostdin", "-i", filename, "-f",
    "s16le", "-acodec", "pcm_s16le", "-ac",
    str(channels), "-ar",
    str(sample_rate), "-"
],
                          stdin=None,
                          stdout=subprocess.PIPE)
stream = stream_pcm(ffmpeg.stdout)
next(stream)  # start the generator
device.start(stream)
input("Audio file playing in the background. Enter to stop playback: ")
device.close()
ffmpeg.terminate()