Esempio n. 1
0
def main():
    player = Player()
    player.open_stream()

    print("play sine wave")
    synthesizer = Synthesizer(osc1_waveform=Waveform.sine, osc1_volume=1.0, use_osc2=False)
    player.play_wave(synthesizer.generate_constant_wave(440.0, 3.0))
    time.sleep(0.5)

    print("play square wave")
    synthesizer = Synthesizer(osc1_waveform=Waveform.square, osc1_volume=0.8, use_osc2=False)
    player.play_wave(synthesizer.generate_constant_wave(440.0, 3.0))
    time.sleep(0.5)

    print("play triangle wave")
    synthesizer = Synthesizer(osc1_waveform=Waveform.triangle, osc1_volume=0.8, use_osc2=False)
    player.play_wave(synthesizer.generate_constant_wave(440.0, 3.0))
    time.sleep(0.5)

    print("play synthesized wave 1")
    synthesizer = Synthesizer(
        osc1_waveform=Waveform.sawtooth, osc1_volume=1.0,
        use_osc2=True, osc2_waveform=Waveform.sawtooth,
        osc2_volume=0.3, osc2_freq_transpose=6.0,
    )
    player.play_wave(synthesizer.generate_constant_wave(440.0, 3.0))
    time.sleep(0.5)

    print("play synthesized wave 2")
    synthesizer = Synthesizer(
        osc1_waveform=Waveform.square, osc1_volume=1.0,
        use_osc2=True, osc2_waveform=Waveform.sine,
        osc2_volume=0.3, osc2_freq_transpose=3.0,
    )
    player.play_wave(synthesizer.generate_constant_wave(440.0, 3.0))
Esempio n. 2
0
def playVoice(notes):
    player = Player()
    player.open_stream()
    synthesizer = Synthesizer(osc1_waveform=Waveform.triangle, osc1_volume=1.0, use_osc2=False)

    for note in notes:
        player.play_wave(synthesizer.generate_constant_wave(synth(note), .5))
Esempio n. 3
0
def play(chord):
    player = Player()
    player.open_stream()
    synthesizer = Synthesizer(osc1_waveform=Waveform.sine,
                              osc1_volume=0.4,
                              use_osc2=False)
    player.play_wave(synthesizer.generate_chord(chord, 1))
Esempio n. 4
0
def play_beat(t):
    player = Player()
    player.open_stream()
    synthesizer = Synthesizer(osc1_waveform=Waveform.sawtooth,
                              osc1_volume=1.0,
                              use_osc2=False)
    for i in range(int(t / RATE)):
        player.play_wave(synthesizer.generate_chord(['A3'], 0.1))
        time.sleep(float(RATE - 0.1))
Esempio n. 5
0
def play_progression(progression):
    player = Player()
    player.open_stream()
    synthesizer = Synthesizer(osc1_waveform=Waveform.sine,
                              osc1_volume=10.0,
                              use_osc2=False)
    for measure in progression:
        for chord in measure:
            player.play_wave(
                synthesizer.generate_chord(chord[0], abs(chord[1])))
Esempio n. 6
0
def consumer(queue):
    player = Player()
    player.open_stream()

    while True:
        tone = queue.get()

        if tone is None:
            break

        player.play_wave(tone)
Esempio n. 7
0
def main():
    args = parse_args()
    chords = ChordProgression(args.chord)

    player = Player()
    player.open_stream()
    synthesizer = Synthesizer(osc1_waveform=Waveform.triangle,
                              osc1_volume=1.0,
                              use_osc2=False)

    for chord in chords:
        notes = chord.components_with_pitch(root_pitch=3)
        print("Play {}".format(chord))
        player.play_wave(synthesizer.generate_chord(notes, 1.0))
def main(protein_sequence):
    """Plays musical protein sequence."""

    # Create dictionary that will map each amino acid to the various musical properties
    association = {}

    # Generate association between amino acid and musical properties
    association.update(get_association(protein_sequence, hydrophobic_aa, hydrophobic_chords, 'square'))
    association.update(get_association(protein_sequence, less_hydrophobic_aa, less_hydrophobic_notes, 'sine'))
    association.update(get_association(protein_sequence, non_hydrophobic_aa, non_hydrophobic_chords, 'sawtooth'))

    # Create Player and Synthesizer objects to be used when playing protein sequence
    player = Player()
    player.open_stream()
    synthesizer = {
        'polar': {
            'sine': Synthesizer(osc1_waveform=Waveform.sine, osc1_volume=1.0, use_osc2=False),
            'sawtooth': Synthesizer(osc1_waveform=Waveform.sawtooth, osc1_volume=1.0, use_osc2=False),
            'square': Synthesizer(osc1_waveform=Waveform.sawtooth, osc1_volume=1.0, use_osc2=False)
        },
        'nonpolar': {
            'sine': Synthesizer(osc1_waveform=Waveform.sine, osc1_volume=0.5, use_osc2=False),
            'sawtooth': Synthesizer(osc1_waveform=Waveform.sawtooth, osc1_volume=0.5, use_osc2=False),
            'square': Synthesizer(osc1_waveform=Waveform.sawtooth, osc1_volume=0.5, use_osc2=False)
        },
    }

    # writer = Writer()
    # sounds = []

    # Loop through and play out each amino acid in the protein sequence
    for idx, aa in enumerate(protein_sequence):
        if aa not in association:
            continue

        note, instrument, volume, length = association[aa]

        length = length if idx != len(protein_sequence) - 1 else 0.5  # Set length of last note to be 0.5s

        if type(note) == list:  # Play chord
            sound = synthesizer[volume][instrument].generate_chord([notes[n] for n in note], length)
            print_notes(note, aa)
        else:  # Play single note
            sound = synthesizer[volume][instrument].generate_constant_wave(notes[note], length)
            print_notes([note], aa)

        player.play_wave(sound)
Esempio n. 9
0
 def worker():
     player = Player()
     player.open_stream()
     synthesizer = Synthesizer(osc1_waveform=Waveform.sine,
                               osc1_volume=0.7,
                               use_osc2=False)
     return player.play_wave(
         synthesizer.generate_constant_wave(areatone, 0.14))
Esempio n. 10
0
 def eeg_callback(self, path, args):
     lE, lF, rF, rE = args
     print "%s %f %f %f %f" % (path, lE, lF, rF, rE)
     player = Player()
     player.open_stream()
     synthesizer = Synthesizer(osc1_waveform=Waveform.sine,
                               osc1_volume=1.0,
                               use_osc2=False)
     number = ra.uniform(0.2, 1.0)
     player.play_wave(
         synthesizer.generate_constant_wave((lF - 1200) * ((600 - 200) /
                                                           (1200 - 750)) +
                                            200), number)
     player.play_wave(
         synthesizer.generate_constant_wave((rF - 1200) * ((600 - 200) /
                                                           (1200 - 750)) +
                                            200), number)
Esempio n. 11
0
def playPiece(lines: List[TemporalisedLine]):
    mapping, indexLines = asUniqueValues(lines)

    lowerLines = indexLines[0:-1]
    upperLine = indexLines[-1]

    sm = makeSimMap(lowerLines, upperLine)

    player = Player()
    player.open_stream()
    synthesizer = Synthesizer(osc1_waveform=Waveform.triangle, osc1_volume=1.0, use_osc2=False)

    for k in upperLine[0][:-1]:
        toPlay = [synth(mapping[n]) for n in sm[k].union([k])]
        player.play_wave(synthesizer.generate_chord([n for n in toPlay], 1 / len(lines)))

    # Play last note longer
    k = upperLine[0][-1]
    toPlay = [synth(mapping[n]) for n in sm[k].union([k])]
    player.play_wave(synthesizer.generate_chord([n for n in toPlay], 2 / len(lines)))
Esempio n. 12
0
class AudioDebug:
    def __init__(self, pre=["C3", "E3", "G3"], post=["C3", "D3", "F3"]):
        self.pre = pre
        self.post = post
        self.player = Player()
        self.player.open_stream()
        self.synthesizer = Synthesizer(osc1_waveform=Waveform.sine,
                                       osc1_volume=1.0,
                                       use_osc2=False)

    def play_chord(self, chord):
        self.player.play_wave(self.synthesizer.generate_chord(chord, 0.5))

    def __call__(self, func):
        def logic(*args, **kwargs):
            print('pre')
            self.play_chord(self.pre)
            result = func(*args, **kwargs)
            print('post')
            self.play_chord(self.post)
            return result

        return logic
Esempio n. 13
0
def play():
    ####################
    player = Player()
    player.open_stream()
    synthesizer = Synthesizer(osc1_waveform=Waveform.sine, osc1_volume=1.0, use_osc2=False)
    #####################
    chordOrNot = [0,0,0,1]

    #SCALING_FACTOR = 7.0/255 #TODO
    durations = (0.25,0.5)#,0.5,0.75,1.0)
    # TODO: Gaussian

    # Part 0: Chord dictionary
    freq_update = {}
    freq = {'A0': 27.5, 'A#0': 29.14, 'B0': 30.87, 'C1': 32.7, 'C#1': 34.65, 'D1': 36.71, 'D#1': 38.89, 'E1': 41.2, 'F1': 43.65, 'F#1': 46.25, 'G1': 49.0, 'G#1': 51.91, 'A1': 55.0, 'A#1': 58.27, 'B1': 61.74, 'C2': 65.41, 'C#2': 69.3, 'D2': 73.42, 'D#2': 77.78, 'E2': 82.41, 'F2': 87.31, 'F#2': 92.5, 'G2': 98.0, 'G#2': 103.83, 'A2': 110.0, 'A#2': 116.54, 'B2': 123.47, 'C3': 130.81, 'C#3': 138.59, 'D3': 146.83, 'D#3': 155.56, 'E3': 164.81, 'F3': 174.61, 'F#3': 185.0, 'G3': 196.0, 'G#3': 207.65, 'A3': 220.0, 'A#3': 233.08, 'B3': 246.94, 'C4': 261.63, 'C#4': 277.18, 'D4': 293.66, 'D#4': 311.13, 'E4': 329.63, 'F4': 349.23, 'F#4': 369.99, 'G4': 392.0, 'G#4': 415.3, 'A4': 440.0, 'A#4': 466.16, 'B4': 493.88, 'C5': 523.25, 'C#5': 554.37, 'D5': 587.33, 'D#5': 622.25, 'E5': 659.26, 'F5': 698.46, 'F#5': 739.99, 'G5': 783.99, 'G#5': 830.61, 'A5': 880.0, 'A#5': 932.33, 'B5': 987.77, 'C6': 1046.5, 'C#6': 1108.73, 'D6': 1174.66, 'D#6': 1244.51, 'E6': 1318.51, 'F6': 1396.91, 'F#6': 1479.98, 'G6': 1567.98, 'G#6': 1661.22, 'A6': 1760.0, 'A#6': 1864.66, 'B6': 1975.53, 'C7': 2093.0, 'C#7': 2217.46, 'D7': 2349.32, 'D#7': 2489.02, 'E7': 2637.02, 'F7': 2793.83, 'F#7': 2959.96, 'G7': 3135.96, 'G#7': 3322.44, 'A7': 3520.0, 'A#7': 3729.31, 'B7': 3951.07, 'C8': 4186.01}
    for k,v in freq.items():
        note = k[:-1]
        octave = int(k[-1])
        freq = v
        if octave == 4:
            freq_update[note] = freq
    freq = freq_update

    # Part 1: Choose a scale. Extract the notes and chords from that scale.
    #all_possible_scales = list(Scale.all('major'))
    m = 'major'
    all_possible_scales = [Scale('C4',m), Scale('A4',m), Scale('F4',m), Scale('G4',m)]
    choice_of_scale = random.choice(all_possible_scales)
    notes = [choice_of_scale[i] for i in range(len(choice_of_scale))]

    # Part 2: Choose a permutation of chords and notes from the list.

    ## Once it is over, pick a new random permutation and keep going unless stopped.

    # Part 3: Go through the image and based on pixed values, play the permutation.
    # Part 3 -->

    image = cv2.imread('images/nature.jpg', 0)

    #image = str(request.get('img'))

    image = skimage.measure.block_reduce(image, (150,150), np.mean)
    image = image.flatten()
    # pooling stuff happens here

    image = np.random.permutation(image)


    for px in image: #px is the pixel value
        if px == 255:
            px = px-1
        isChord = random.choice(chordOrNot)
        note = math.trunc(px*len(notes)/255.0)
        duration = random.choice(durations)
        if note >= len(notes):
            continue
        note = str(notes[note])

        if note not in freq:
            flatOrSharp = note[-1]
            if flatOrSharp == '#':
                note = chr(ord(note[0])+1)
            else:
                note = chr(ord(note[0])-1)
        
        if note not in freq:
            continue
        fr = freq[note]
        if(isChord):
            # play a chord
            notes_in_chord = Chord(Note(note), 'M').notes
            freq_list = []
            for n in notes_in_chord:
                a = str(n)
                if a not in freq:
                    flatOrSharp = a[-1]
                    if flatOrSharp == '#':
                        a = chr(ord(a[0])+1)
                    else:
                        a = chr(ord(a[0])-1)
                        if a not in freq:
                            break
                freq_list.append(freq[a])
            player.play_wave(synthesizer.generate_chord(freq_list, duration))
        else:
            # play a note
            player.play_wave(synthesizer.generate_constant_wave(fr, duration))
    return "Successfully vocalized image";
Esempio n. 14
0
    note = 2**((note_num-69)/12.0)*440

    if(midi_dat[0][0] != 144):
        return list_in, num_list
    if(midi_dat[0][2] == 0):
        try:
            while(True):
                ind = num_list.index(note_num)
                if ind != -1:
                    list_in.pop(ind)
                    num_list.pop(ind)
        except: 
            return list_in, num_list
    else:
        list_in += [note]
        num_list += [note_num]
    return list_in, num_list
    

while(True):
    if(i.poll()):
        # read = midi.device.read(1)[0];
        read = i.read(10)[0]
        # print(read)
        # if(read[0][0] == 144 and read[0][1] != 0):
        #     val = int(read[0][1]);

        note_list, num_list = update_list(note_list, num_list, read)
    if(len(note_list) > 0):
        player.play_wave(synthesizer.generate_chord(note_list, 0.1)) # using chord to be able to play more notes as once
Esempio n. 15
0
from synthesizer import Player, Synthesizer, Waveform

p = Player()
p.open_stream()

s = Synthesizer(osc1_waveform=Waveform.sine, osc1_volume=1.0, use_osc2=False)

i = 0
while (i < 3):
    A = s.generate_constant_wave(88.0, 1.0)
    p.play_wave(A)
    i += 1
from synthesizer import Player, Synthesizer, Waveform
import numpy as np

player = Player()
player.open_stream()
synthesizer = Synthesizer(osc1_waveform=Waveform.square,
                          osc1_volume=1.0,
                          use_osc2=True)
blank = synthesizer.generate_constant_wave(0, 0.5)
bass = synthesizer.generate_constant_wave(146.83, 0.5)
synthesizer2 = Synthesizer(osc2_waveform=Waveform.square,
                           osc2_volume=1.0,
                           use_osc2=True)
melodi = synthesizer.generate_constant_wave(261.63, 0.5)
instrumenter = [blank, bass, melodi]

grid = [[True, False], [False, True], [True, True], [False, True]]

for takt in grid:
    for instrument in range(0, len(takt)):
        out = blank
        if takt[instrument] == True:
            out = out + instrumenter[instrument]
        if out.equals(blank):  # Find ud af at sammenligne numpy arrays (type?)
            player.play_wave(out)
Esempio n. 17
0
import time
from synthesizer import Player, Synthesizer, Waveform, Oscillator
""" Emergency sound maker for when Helm isn't working"""


def midi_to_freq(note):
    a = 440  #frequency of A (common value is 440Hz)
    return (a / 32) * (2**((note - 9) / 12))


player = Player()
player.open_stream()
synthesizer = Synthesizer(osc1_waveform=Waveform.sine,
                          osc1_volume=0.25,
                          use_osc2=False)
oscillator = Oscillator(Waveform.sine, volume=0.25)

prev_note = 440

with mido.open_input() as port:
    for message in port:
        if message.type == 'note_on':
            current_time = time.time()
            note = message.note
            freq = message.note * 10
            print(message)

            player.play_wave(synthesizer.generate_constant_wave(freq, 0.01))

        prev_note = message.note * 10
Esempio n. 18
0
timeout = time.time() + 35  #seconds 32-35 is ok
print("Timer engaged")
while True:
    # timer to break the loop
    if time.time() > timeout:
        print("Timer finished")
        break

    # try/except to avoid errors while writing and reading at the same time
    try:
        with open("../input/outfile_area", "rb") as fa:
            area_out = pickle.load(fa)
            areatone, note = deep_purple(area_out)
            print(areatone, " Hz")
            notes.append(note)
            player.play_wave(synthesizer.generate_constant_wave(
                areatone, 0.05))
            #areatone,note = transforming_to_tones(area_out)
            #areatone = theremin(area_out)
            #areatone, note = mama_isnt_home(area_out)
            #areatone, note=chosen_scale
    except:
        print("Hand frame casualty")

print("-----42-----")
print("Plotting notes:")

# Plotting notes.
plotting_notes(notes)
print("Plots saved with .PDF format in input folder")

# take a glance to what's written in just_video.py
Esempio n. 19
0
from synthesizer import Player, Synthesizer, Waveform

player = Player()
player.open_stream()

# 以下をexcelからコピペする
arr = [(523, 0.375), (0, 0.0535714285714286), (523, 0.428571428571429),
       (784, 0.375), (0, 0.0535714285714286), (784, 0.428571428571429),
       (880, 0.375), (0, 0.0535714285714286), (880, 0.428571428571429),
       (784, 0.857142857142857), (698, 0.375), (0, 0.0535714285714286),
       (698, 0.428571428571429), (659, 0.375), (0, 0.0535714285714286),
       (659, 0.428571428571429), (587, 0.375), (0, 0.0535714285714286),
       (587, 0.428571428571429), (523, 0.857142857142857)]
arr = [(659, 0.4), (494, 0.2), (523, 0.2), (587, 0.4), (523, 0.2), (494, 0.2),
       (440, 0.35), (0, 0.05), (440, 0.2), (523, 0.2), (659, 0.4), (587, 0.2),
       (523, 0.2), (494, 0.35), (0, 0.05), (494, 0.2), (523, 0.2), (587, 0.4),
       (659, 0.4), (523, 0.4), (440, 0.3), (0, 0.1), (440, 0.6), (0, 0.4),
       (587, 0.4), (698, 0.2), (880, 0.4), (784, 0.2), (698, 0.2), (659, 0.35),
       (0, 0.05), (659, 0.2), (523, 0.2), (659, 0.35), (0, 0.05), (587, 0.2),
       (523, 0.2), (494, 0.35), (0, 0.05), (494, 0.2), (523, 0.2), (587, 0.4),
       (659, 0.4), (523, 0.4), (440, 0.35), (0, 0.05), (440, 0.8)]

synth = Synthesizer(osc1_waveform=Waveform.sine,
                    osc1_volume=1.0,
                    use_osc2=False)
for p in arr:
    player.play_wave(synth.generate_constant_wave(p[0], p[1]))
Esempio n. 20
0
player.open_stream()
instrument1 = osc1_waveform = Waveform.square  #main instrument
instrument2 = osc1_waveform = Waveform.triangle  #diff instrument
volume1 = osc1_volume = 0.5  #nonpolar
volume2 = osc1_volume = 1.0  #polar
length = [0.1, 0.2, .3]  #based on size from smallest to largest

##For loop plays out each individual chords or notes from transcribed music
count = 0
for music in music_sheet:
    if music in chord_freq and aa_sequence[count] in small and aa_sequence[
            count] in nonpolar:  #Chords A-G & small
        print(aa_sequence[count])
        synthesizer = Synthesizer(instrument1, \
                                  volume1,use_osc2=False)
        player.play_wave(
            synthesizer.generate_chord(chord_freq[music], length[0]))
        count += 1
    elif music in chord_freq and aa_sequence[count] in small and aa_sequence[
            count] in polar:  #Chords A-G & small
        print(aa_sequence[count])
        synthesizer = Synthesizer(instrument1, \
                                  volume2,use_osc2=False)
        player.play_wave(
            synthesizer.generate_chord(chord_freq[music], length[0]))
        count += 1
    elif music in chord_freq and aa_sequence[count] in medium and aa_sequence[
            count] in nonpolar:  #Chords A-G & medium
        print(aa_sequence[count])
        synthesizer = Synthesizer(instrument1, \
                                  volume1,use_osc2=False)
        player.play_wave(
#iterate
while True:
    a = psutil.cpu_percent() / 100
    b = psutil.virtual_memory()[2] / 100

    pitch1 = a * (pitches[1] - pitches[0]) + pitches[
        0]  #changes every cycle with no lingering weight
    pitch2 = (1 - weight) * (pitch2) + (
        weight
    ) * pitch1  #weighted average of last n of pitches from pitch1 where n is (1/weight). makes a drone
    pitch3 = np.log(5 * np.exp(pitch2) *
                    (1 / 6))  #makes a minor third below the drone of pitch2
    tempo = b * (tempos[1] - tempos[0]) + tempos[0]  #define tempo from range

    leng = 60 / tempo
    chord = synthesizer.generate_chord(
        [np.exp(pitch1), np.exp(pitch2),
         np.exp(pitch3)], leng)  #second arg is length

    #make chord not clip on or off, fade first and last values
    lengthFade = int(fadeParam * len(chord))

    fadeVec = np.linspace(0, 1, num=lengthFade)
    chord[:lengthFade] = chord[:lengthFade] * fadeVec

    fadeVec = np.linspace(1, 0, num=lengthFade)
    chord[-lengthFade:] = chord[-lengthFade:] * fadeVec

    player.play_wave(chord)
from synthesizer import Player, Synthesizer, Waveform

from common.tones import Chord, Intervals, Tones

from common import tones

player = Player()
player.open_stream()
synthesizer = Synthesizer(osc1_waveform=Waveform.sine,
                          osc1_volume=1.0,
                          use_osc2=False)
# Play A4
player.play_wave(synthesizer.generate_constant_wave(Tones.A4_freq, 1.0))

player.play_wave(
    synthesizer.generate_chord(
        tones.Chord.freqs_mult(Tones.A4_freq, Chord.Type.major), 2.0))
player.play_wave(
    synthesizer.generate_chord(
        tones.Chord.freqs_mult(Tones.A4_freq, Chord.Type.minor), 2.0))
player.play_wave(
    synthesizer.generate_chord(
        tones.Chord.freqs_mult(Tones.A4_freq, Chord.Type.dim), 2.0))
player.play_wave(
    synthesizer.generate_chord(
        tones.Chord.freqs_mult(Tones.A4_freq, Chord.Type.aug), 2.0))

# Play C major
player.play_wave(synthesizer.generate_chord(Chord.C_major_chord, 3.0))
Esempio n. 23
0
import genome

if __name__ == '__main__':
    player = Player()
    player.open_stream()
    synthesizer = Synthesizer(osc1_waveform=Waveform.sine,
                              osc1_volume=1.0,
                              use_osc2=False)

    w = 0.5  # weight for frequency transposition (0.5 = one octave lower)
    l = 0.05  # duration of each note

    nuc_freqs = {
        'a': 440.00 * w,
        'g': 392.00 * 2 * w,
        'c': 523.25 * w,
        't': 2793 * w
    }

    merge_repeated_nucleotides = True

    if (merge_repeated_nucleotides):
        for nuc_seg in genome.segments():
            player.play_wave(
                synthesizer.generate_constant_wave(nuc_freqs[nuc_seg[0]],
                                                   l * nuc_seg[1]))
    else:
        for nucleotide in genome.sequence():
            player.play_wave(
                synthesizer.generate_constant_wave(nuc_freqs[nucleotide], l))
Esempio n. 24
0
H = 'D'
L = 'E'
T = 'F'
P = 'G'
'''

# MVHLTPEE into chords, chords in pyaudio are in the form of frequencies
# Link to frequency chart: http://pages.mtu.edu/~suits/notefreqs.html
B = [493.88, 311.13,
     369.99]  # B major consists of the notes B, D#, F# with these given freq.
C = [261.63, 329.63,
     392.00]  # C major consists of C, E, G with these given frequencies
D = [293.66, 369.99, 440.00]  # D major consists of D, F#, A
E = [329.63, 415.30, 493.88]  # etc...
F = [349.23, 440.00, 261.63]
G = [392.00, 493.88, 293.66]
A = [440.00, 277.18, 329.63]

# So our major chord sequence for our amino acid sequence is: BCDEFGAA

major_chords = [B, C, D, E, F, G, A, A]  # List the major chords sequence
for letter in major_chords:  # For each major chord, play the sound of that major chord using the
    # listed frequencies from earlier^
    player = Player()
    player.open_stream()
    synthesizer = Synthesizer(osc1_waveform=Waveform.sawtooth,
                              osc1_volume=1.0,
                              use_osc2=False)
    chord = letter
    player.play_wave(synthesizer.generate_chord(chord, 0.5))
Esempio n. 25
0
def main():
    player = Player()
    player.open_stream()

    print("play major chord")
    synthesizer = Synthesizer(osc1_waveform=Waveform.sine,
                              osc1_volume=1.0,
                              use_osc2=False)
    chord = ["C4", "E4", "G4"]
    player.play_wave(synthesizer.generate_chord(chord, 3.0))
    time.sleep(0.5)

    print("play minor chord")
    chord = ["C4", "Eb4", "G4"]
    player.play_wave(synthesizer.generate_chord(chord, 3.0))
    time.sleep(0.5)

    print("play sus4 chord")
    chord = ["C4", "F4", "G4"]
    player.play_wave(synthesizer.generate_chord(chord, 3.0))
    time.sleep(0.5)

    print("play 7th chord")
    chord = ["C4", "E4", "G4", "Bb4"]
    player.play_wave(synthesizer.generate_chord(chord, 3.0))
    time.sleep(0.5)

    print("play add9 chord")
    chord = ["C4", "E4", "G4", "D5"]
    player.play_wave(synthesizer.generate_chord(chord, 3.0))
    time.sleep(0.5)

    print("play chord sequence")
    chord = ["D4", "F4", "A4", "C5"]
    player.play_wave(synthesizer.generate_chord(chord, 1.0))
    chord = ["D4", "G4", "B4"]
    player.play_wave(synthesizer.generate_chord(chord, 1.0))
    chord = ["E4", "G4", "C5"]
    player.play_wave(synthesizer.generate_chord(chord, 1.0))
Esempio n. 26
0
"""
    Synthesize a simple sound of a given frequency.
"""
from synthesizer import Player, Synthesizer, Waveform, Writer
import scales

player = Player()
player.open_stream()
synthesizer = Synthesizer(osc1_waveform=Waveform.sine, osc1_volume=1.0, use_osc2=False)

# Play A4
player.play_wave(synthesizer.generate_constant_wave(440.0, 1.0))

# Play C major
chord = [261.626,  329.628, 391.996]
player.play_wave(synthesizer.generate_chord(chord, 1.0))

# Play exemplary "almost" chord
# C_4
chord = [270.000,  329.628, 370.000]
player.play_wave(synthesizer.generate_chord(chord, 2.0))

# write
writer = Writer()

chord = [170.000,  329.628, 570.000]
wave = synthesizer.generate_chord(chord, 3.0)
writer.write_wave("output_records/synth.wav", wave)

# # generate the sound of a full scale of notes
# scale_dict = scales.fit_frequencies(scales.full_scale)
class MelodyPlayer(object):
    """
    A class used to play the melody generated by Melody

    Attributes
    ----------
    player : Player
        an object that plays the melody
    synthesizer : Synthesizer
        an object that characterizes the sound of the melody
    """
    def __init__(self, oscillator):
        """
        Instantiate the synthesizer and the player

        Parameters
        ----------
        oscillator : str
            defines the shape of the Waveform
        """

        self.player = Player()

        self.synthesizer = Synthesizer(osc1_waveform=WAVEFORM[oscillator])

    def play_melody(self, melody, bpm):
        """
        Plays the melody in a certain bpm

        Parameters
        ----------
        melody : Melody
            the melody that will be played
        bpm : int
            beats per minute that determine the speed the melody is played
        """

        self.player.open_stream()

        for note in melody.notes:
            wave_sound = self.generate_waves(note, bpm)
            self.player.play_wave(wave_sound)

    def save_melody(self, melody, bpm):
        """
        Saves the melody as WAV

        Saves each note individually and then concatenate then
        in a sigle WAV file

        Parameters
        ----------
        melody : Melody
            the melody that will be played
        bpm : int
            beats per minute that of the melody
        """

        writer = Writer()
        outfile = "melody.wav"
        next_note = "note.wav"
        data = []

        for note in melody.notes:
            sound = self.generate_waves(note, bpm)

            if note == melody.notes[0]:
                # Generates the first note
                writer.write_wave(outfile, sound)
                continue

            writer.write_wave(next_note, sound)

            infiles = [outfile, next_note]

            for infile in infiles:
                with wave.open(infile, 'rb') as w:
                    data.append([w.getparams(), w.readframes(w.getnframes())])

            self.append_note(outfile, data)

            # Deletes the note file
            os.remove(next_note)

    @staticmethod
    def append_note(outfile, data):
        """
        Auxiliary method for save_melody

        Code found on https://bit.ly/2EoFjIU

        Parameters
        ----------
        outfile : str
            path to output file
        data : list
            an array of WAV parameters
        """

        with wave.open(outfile, 'wb') as output:
            output.setparams(data[0][0])
            output.writeframes(data[0][1])
            output.writeframes(data[1][1])

        data.clear()

    def generate_waves(self, note, bpm):
        """
        Generate the wave that represents a note

        Parameters
        ---------
        note : MusicalNote
            The note that will be turned into wave
        bpm : int
            beats per minute that determines the lenght

        Returns
        -------
        ndarray
            an array that represents the normalized wave
        """

        lenght = note.lenght["duration"] / 16 * 60 / bpm

        # If the note is not played, the frequency is 0
        frequency = note.note["frequency"] if note.is_played else 0

        return self.synthesizer.generate_constant_wave(frequency, lenght)
Esempio n. 28
0
def digitalChime(number_of_notes):
    player = Player()
    synthesizer = Synthesizer(osc1_waveform=Waveform.sawtooth,
                              osc1_volume=0.1,
                              use_osc2=False)
    player.open_stream()

    #find base note
    base = random.randint(1, 6)
    time = random.randint(1, 4) * 0.25

    octive = 1
    sig = 3

    #play this many notes
    for i in range(0, number_of_notes):
        next = random.randint(1, 6)

        print('|  ', end='')

        if i % sig == 0:
            base = random.randint(1, 6)
            if base == 1:
                base = Notes['C4']
                print('Cv ', end='♪ ')
            elif base == 2:
                base = Notes['D4']
                print('Dv ', end='♪ ')
            elif base == 3:
                base = Notes['F4']
                print('Fv ', end='♪ ')
            elif base == 4:
                base = Notes['G4']
                print('Gv ', end='♪ ')
            elif base == 5:
                base = Notes['A4']
                print('Av ', end='♪ ')
            else:
                base = Notes['C5']
                print('C  ', end='♪ ')
            base = (base / 2) * octive
        else:
            print('"  ', end='♫ ')

        if next == 1:
            next = Notes['C4']
            print('C  ', end='')
        elif next == 2:
            next = Notes['D4']
            print('D  ', end='')
        elif next == 3:
            next = Notes['F4']
            print('F  ', end='')
        elif next == 4:
            next = Notes['G4']
            print('G  ', end='')
        elif next == 5:
            next = Notes['A4']
            print('A  ', end='')
        else:
            next = Notes['C5']
            print('C^ ', end='')

        if i % (int)(8 / (time)) == 0:
            print(' | ', end='♫ ')
            sig = random.randint(2, 8)
            time = random.randint(2, 10) * 0.125
            octive = random.randint(0, 2)
            if octive == 0:
                octive = 0.5
            elif octive < 0:
                octive = 0.25
            print(octive * 4, end=' ♪ ')
            print(time, end=' ♪\n')
        else:
            print(' |')

        next *= octive
        chord = [next, base]

        #print(octive)
        #print(time)

        player.play_wave(synthesizer.generate_chord(chord, time))
        # player.play_wave(synthesizer.generate_constant_wave(next,0.5))

    player.play_wave(synthesizer.generate_chord(chord, time * sig - 1))
Esempio n. 29
0
    print(note_string)


association.update(get_association(protein_sequence, hydrophobic_aa, major_chords))
association.update(get_association(protein_sequence, less_hydrophobic_aa, single_notes))
association.update(get_association(protein_sequence, part_hydrophobic_aa, extra_chords, 'sawtooth'))
association.update(get_association(protein_sequence, non_hydrophobic_aa, minor_chords))

# print(association)

player = Player()
player.open_stream()
synthesizer = {
    'sine': Synthesizer(osc1_waveform=Waveform.sine, osc1_volume=1.0, use_osc2=False),
    'sawtooth': Synthesizer(osc1_waveform=Waveform.sawtooth, osc1_volume=1.0, use_osc2=False)
}

for idx, aa in enumerate(protein_sequence):
    note, instrument = association[aa]

    length = 0.2 if idx != len(protein_sequence) - 1 else 1

    if type(note) == list:
        sound = synthesizer[instrument].generate_chord([notes[n] for n in note], length)
        print_notes(note)
    else:
        sound = synthesizer[instrument].generate_constant_wave(notes[note], length)
        print_notes([note])

    player.play_wave(sound)
Esempio n. 30
0
def main():
    player = Player()
    player.open_stream()

    print("play major chord")
    synthesizer = Synthesizer(osc1_waveform=Waveform.sine,
                              osc1_volume=1.0,
                              use_osc2=False)
    chord = [BASE, BASE * 2.0**(4 / 12.0), BASE * 2.0**(7 / 12.0)]
    player.play_wave(synthesizer.generate_chord(chord, 3.0))
    time.sleep(0.5)

    print("play minor chord")
    chord = [BASE, BASE * 2.0**(3 / 12.0), BASE * 2.0**(7 / 12.0)]
    player.play_wave(synthesizer.generate_chord(chord, 3.0))
    time.sleep(0.5)

    print("play sus4 chord")
    chord = [BASE, BASE * 2.0**(5 / 12.0), BASE * 2.0**(7 / 12.0)]
    player.play_wave(synthesizer.generate_chord(chord, 3.0))
    time.sleep(0.5)

    print("play 7th chord")
    chord = [
        BASE, BASE * 2.0**(4 / 12.0), BASE * 2.0**(7 / 12.0),
        BASE * 2.0**(10 / 12.0)
    ]
    player.play_wave(synthesizer.generate_chord(chord, 3.0))
    time.sleep(0.5)

    print("play add9 chord")
    chord = [
        BASE, BASE * 2.0**(4 / 12.0), BASE * 2.0**(7 / 12.0),
        BASE * 2.0**(14 / 12.0)
    ]
    player.play_wave(synthesizer.generate_chord(chord, 3.0))
    time.sleep(0.5)

    print("play chord sequence")
    chord = [
        BASE * 2.0**(2 / 12.0), BASE * 2.0**(5 / 12.0), BASE * 2.0**(9 / 12.0),
        BASE * 2.0**(12 / 12.0)
    ]
    player.play_wave(synthesizer.generate_chord(chord, 1.0))
    chord = [
        BASE * 2.0**(2 / 12.0), BASE * 2.0**(7 / 12.0), BASE * 2.0**(11 / 12.0)
    ]
    player.play_wave(synthesizer.generate_chord(chord, 1.0))
    chord = [
        BASE, BASE * 2.0**(4 / 12.0), BASE * 2.0**(7 / 12.0),
        BASE * 2.0**(12 / 12.0)
    ]
    player.play_wave(synthesizer.generate_chord(chord, 1.0))