Exemple #1
0
def play_console(filename_or_stream):
    with wave.open(filename_or_stream, 'r') as wav:
        samplewidth = wav.getsampwidth()
        samplerate = wav.getframerate()
        nchannels = wav.getnchannels()
        bar_width = 60
        update_rate = 20  # lower this if you hear the sound crackle!
        levelmeter = LevelMeter(rms_mode=False, lowest=-50.0)
        with Output(samplerate, samplewidth, nchannels,
                    int(update_rate / 4)) as out:
            while True:
                frames = wav.readframes(samplerate // update_rate)
                if not frames:
                    break
                sample = Sample.from_raw_frames(frames, wav.getsampwidth(),
                                                wav.getframerate(),
                                                wav.getnchannels())
                out.play_sample(sample, async=True)
                levelmeter.update(sample)
                time.sleep(
                    sample.duration * 0.4
                )  # print the peak meter more or less halfway during the sample
                levelmeter.print(bar_width)
    print("\ndone")
    input("Enter to exit:")
Exemple #2
0
def demo_tones():
    synth = WaveSynth()
    with Output(nchannels=1) as out:
        for wave in [
                synth.square_h, synth.square, synth.sine, synth.triangle,
                synth.sawtooth, synth.sawtooth_h
        ]:
            print(wave.__name__)
            for note, freq in list(notes[4].items())[6:]:
                print("   {:f} hz".format(freq))
                sample = wave(freq, duration=0.4).fadein(0.02).fadeout(0.1)
                out.play_sample(sample)
        print("pulse")
        for note, freq in list(notes[4].items())[6:]:
            print("   {:f} hz".format(freq))
            sample = synth.pulse(freq, duration=0.4,
                                 pulsewidth=0.1).fadein(0.02).fadeout(0.1)
            out.play_sample(sample)
        print("harmonics (only even)")
        for note, freq in list(notes[3].items())[6:]:
            print("   {:f} hz".format(freq))
            harmonics = [(n, 1 / n) for n in range(1, 5 * 2, 2)]
            sample = synth.harmonics(freq, 0.4,
                                     harmonics).fadein(0.02).fadeout(0.1)
            out.play_sample(sample)
        print("noise")
        sample = synth.white_noise(duration=1.5).fadein(0.1).fadeout(0.1)
        out.play_sample(sample)
Exemple #3
0
def main(args):
    if len(args) < 1:
        raise SystemExit(
            "Mixes one or more audio files. Arguments: inputfile...")
    hqresample = AudiofileToWavStream.supports_hq_resample()
    if not hqresample:
        print(
            "WARNING: ffmpeg isn't compiled with libsoxr, so hq resampling is not supported."
        )
    wav_streams = [
        AudiofileToWavStream(filename, hqresample=hqresample)
        for filename in args
    ]
    with StreamMixer(wav_streams, endless=True) as mixer:
        mixed_samples = iter(mixer)
        with Output(mixer.samplerate, mixer.samplewidth,
                    mixer.nchannels) as output:
            levelmeter = LevelMeter(rms_mode=False, lowest=-50)
            temp_stream = AudiofileToWavStream("samples/909_crash.wav",
                                               hqresample=hqresample)
            for timestamp, sample in mixed_samples:
                levelmeter.update(sample)
                output.play_sample(sample)
                time.sleep(sample.duration * 0.4)
                levelmeter.print(bar_width=60)
                if 5.0 <= timestamp <= 5.1:
                    mixer.add_stream(temp_stream)
                if 10.0 <= timestamp <= 10.1:
                    sample = Sample("samples/909_crash.wav").normalize()
                    mixer.add_sample(sample)
    print("done.")
Exemple #4
0
def demo_song():
    synth = WaveSynth()
    notes = {
        note: key_freq(49 + i)
        for i, note in enumerate(
            ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'])
    }
    tempo = 0.3

    def instrument(freq, duration):
        harmonics = [(1, 1), (2, 1 / 2), (4, 1 / 4), (6, 1 / 6)]
        a = synth.harmonics(freq, duration, harmonics)
        return a.envelope(0.05, 0.2, 0.8, 0.5)

    print("Synthesizing tones...")
    quarter_notes = {note: instrument(notes[note], tempo) for note in notes}
    half_notes = {note: instrument(notes[note], tempo * 2) for note in notes}
    full_notes = {note: instrument(notes[note], tempo * 4) for note in notes}
    song = "A A B. A D. C#.. ;  A A B. A E. D.. ;  A A A. F#.. D C#.. B ;  G G F#.. D E D ; ; "\
        "A A B. A D C#.. ; A A B. A E D. ; A A A. F#.. D C#.. B ; G G F#.. D E D ; ; "
    with Output(synth.samplerate, synth.samplewidth, 1) as out:
        for note in song.split():
            if note == ";":
                print()
                time.sleep(tempo * 2)
                continue
            print(note, end="  ", flush=True)
            if note.endswith(".."):
                sample = full_notes[note[:-2]]
            elif note.endswith("."):
                sample = half_notes[note[:-1]]
            else:
                sample = quarter_notes[note]
            out.play_sample(sample)
        print()
Exemple #5
0
def echo_sample():
    synth = WaveSynth(samplerate=22050)
    lfo = Linear(1, -0.0001, min_value=-99999)
    s = synth.pulse(220, .5, fm_lfo=lfo).fadeout(.2)
    with Output(s.samplerate, s.samplewidth, s.nchannels) as out:
        e = s.copy().echo(1, 4, 0.5, 0.4)  # echo
        out.play_sample(e)
        e = s.copy().echo(
            1, 30, 0.15,
            0.5)  # simple "reverberation" (simulated using fast echos)
        out.play_sample(e)
Exemple #6
0
def envelope():
    from matplotlib import pyplot as plot
    synth = WaveSynth()
    freq = 440
    s = synth.triangle(freq, duration=1)
    s.envelope(0.05, 0.1, 0.6, 0.4)
    plot.title("ADSR envelope")
    plot.plot(s.get_frame_array())
    plot.show()
    with Output(nchannels=1) as out:
        out.play_sample(s)
Exemple #7
0
def modulate_amp():
    from matplotlib import pyplot as plot
    synth = WaveSynth()
    freq = 220
    s1 = synth.triangle(freq, duration=2)
    m = synth.sine(2, duration=2, amplitude=0.4, bias=0.5)
    s1.modulate_amp(m)
    plot.title("Amplitude modulation by another waveform")
    plot.plot(s1.get_frame_array())
    plot.show()
    with Output(nchannels=1) as out:
        out.play_sample(s1)
    s1 = synth.triangle(freq, duration=2)
    m = Sine(3, amplitude=0.4, bias=0.5)
    s1.modulate_amp(m)
    plot.title("Amplitude modulation by an oscillator")
    plot.plot(s1.get_frame_array())
    plot.show()
    with Output(nchannels=1) as out:
        out.play_sample(s1)
Exemple #8
0
 def __init__(self, app):
     self.app = app
     self.app.after(self.update_rate, self.tick)
     self.app.firstTrackFrame.play()
     self.stopping = False
     self.mixer = StreamMixer([], endless=True)
     self.output = Output(self.mixer.samplerate,
                          self.mixer.samplewidth,
                          self.mixer.nchannels,
                          queuesize=self.async_queue_size)
     self.mixed_samples = iter(self.mixer)
     self.levelmeter = LevelMeter(rms_mode=False,
                                  lowest=self.levelmeter_lowest)
Exemple #9
0
 def open_audio_file(self, filename_or_stream):
     self.wave = wave.open(filename_or_stream, 'r')
     self.samplewidth = self.wave.getsampwidth()
     self.samplerate = self.wave.getframerate()
     self.nchannels = self.wave.getnchannels()
     self.levelmeter = LevelMeter(rms_mode=False, lowest=self.lowest_level)
     self.audio_out = Output(self.samplerate, self.samplewidth,
                             self.nchannels, int(self.update_rate / 4))
     filename = filename_or_stream if isinstance(filename_or_stream,
                                                 str) else "<stream>"
     info = "Source:\n{}\n\nRate: {:g} Khz\nBits: {}\nChannels: {}".format(
         filename, self.samplerate / 1000, 8 * self.samplewidth,
         self.nchannels)
     self.info.configure(text=info)
Exemple #10
0
def vibrato():
    synth = WaveSynth()
    duration = 3

    def make_sample(freq):
        fmfm = Linear(0, 0.002, max_value=99999)
        fm = Sine(0.05, amplitude=0.5, fm_lfo=fmfm)
        s1 = synth.sawtooth(freq, duration, amplitude=0.6, fm_lfo=fm)
        s1.envelope(0.01, 0.1, 0.6, 2)
        return s1

    with Output(synth.samplerate, nchannels=1) as out:
        for f in [220, 330, 440]:
            sample = make_sample(f)
            out.play_sample(sample)
Exemple #11
0
def chords():
    synth = WaveSynth()
    with Output(nchannels=1) as out:
        for rootnote in octave_notes:
            chord_keys = major_chord_keys(rootnote, 4)
            print("chord", rootnote, [
                "{0} {1}".format(note, octave) for note, octave in chord_keys
            ])
            freqs = [notes[octave][key] for key, octave in chord_keys]
            for i in range(1, len(freqs)):
                assert freqs[i] > freqs[i - 1]
            samples = [
                synth.sine(freq, 1.5, amplitude=0.333) for freq in freqs
            ]
            s = samples[0].mix(samples[1]).mix(
                samples[2]).fadein(0.1).fadeout(0.1)
            out.play_sample(s)
Exemple #12
0
def pwm():
    from matplotlib import pyplot as plot
    synth = WaveSynth(samplerate=1000)
    pwm_lfo = Sine(0.05, amplitude=0.49, bias=0.5, samplerate=synth.samplerate)
    s1 = synth.pulse(4, amplitude=0.6, duration=20, pwm_lfo=pwm_lfo)
    plot.figure(figsize=(16, 4))
    plot.title("Pulse width modulation")
    plot.ylim([-35000, 35000])
    plot.plot(s1.get_frame_array())
    plot.show()
    with Output(nchannels=1) as out:
        synth = WaveSynth()
        lfo2 = Sine(0.2, amplitude=0.48, bias=0.5)
        s1 = synth.pulse(440 / 6,
                         amplitude=0.5,
                         duration=6,
                         fm_lfo=None,
                         pwm_lfo=lfo2)
        out.play_sample(s1)
Exemple #13
0
def fm():
    synth = WaveSynth(samplerate=8000)
    from matplotlib import pyplot as plot
    freq = 2000
    lfo1 = Sine(1, amplitude=0.4, samplerate=synth.samplerate)
    s1 = synth.sine(freq, duration=3, fm_lfo=lfo1)
    plot.title("Spectrogram")
    plot.ylabel("Freq")
    plot.xlabel("Time")
    plot.specgram(s1.get_frame_array(),
                  Fs=synth.samplerate,
                  noverlap=90,
                  cmap=plot.cm.gist_heat)
    plot.show()
    with Output(nchannels=1, samplerate=22050) as out:
        synth = WaveSynth(samplerate=22050)
        freq = 440
        lfo1 = Linear(5, samplerate=synth.samplerate)
        lfo1 = EnvelopeFilter(lfo1, 1, 0.5, 0.5, 0.5, 1)
        s1 = synth.sine(freq, duration=3, fm_lfo=lfo1)
        s_all = s1.copy()
        out.play_sample(s1)
        lfo1 = Sine(1, amplitude=0.2, samplerate=synth.samplerate)
        s1 = synth.sine(freq, duration=2, fm_lfo=lfo1)
        s_all.join(s1)
        out.play_sample(s1)
        lfo1 = Sine(freq / 17, amplitude=0.5, samplerate=synth.samplerate)
        s1 = synth.sine(freq, duration=2, fm_lfo=lfo1)
        s_all.join(s1)
        out.play_sample(s1)
        lfo1 = Sine(freq / 6, amplitude=0.5, samplerate=synth.samplerate)
        s1 = synth.sine(freq, duration=2, fm_lfo=lfo1)
        s_all.join(s1)
        out.play_sample(s1)
        lfo1 = Sine(1, amplitude=0.4, samplerate=synth.samplerate)
        s1 = synth.triangle(freq, duration=2, fm_lfo=lfo1)
        s_all.join(s1)
        out.play_sample(s1)
        freq = 440 * 2
        lfo1 = Sine(freq / 80, amplitude=0.4, samplerate=synth.samplerate)
        s1 = synth.triangle(freq, duration=2, fm_lfo=lfo1)
        s_all.join(s1)
        out.play_sample(s1)
Exemple #14
0
def main(track_file, outputfile=None, interactive=False):
    discard_unused = not interactive
    if interactive:
        repl = Repl(discard_unused_instruments=discard_unused)
        repl.do_load(track_file)
        repl.cmdloop("Interactive Samplebox session. Type 'help' for help on commands.")
    else:
        song = Song()
        song.read(track_file, discard_unused_instruments=discard_unused)
        with Output() as out:
            if out.supports_streaming:
                # mix and stream output in real time
                print("Mixing and streaming to speakers...")
                out.play_samples(song.mix_generator(), False)
                print("\r                          ")
            else:
                # output can't stream, fallback on mixing everything to a wav
                print("(Sorry, streaming audio is not possible, perhaps because you don't have pyaudio installed?)")
                song.mix(outputfile)
                mix = Sample(wave_file=outputfile)
                print("Playing sound...")
                out.play_sample(mix)