示例#1
0
def playnotes(namesOrNotes=['C3', 'E3', 'G3', 'C4'],
              length=2.0,
              delay=0.05,
              volume=0.25):
    '''
    Plays the notes passed in on the digitar (digital-guitar).
    
    Parameters:
            namesOrNotes: Represents the notes to be played in one of these -
                    1 - a string naming a note, like 'C3', 'D#4', or 'Bb2',
                    2 - a list of strings naming the notes as above,
                    3 - a Note instance, or
                    4 - a list of Note instances.
                Defaults to ['C3', 'E3', 'G3', 'C4'] - it's a nice sounding chord.
            length: If not using Note instance(s), defines how long each note will be held for, in seconds.
                Defaults to 2.0 seconds.
            delay: If a list of strings is passed in, defines how many seconds to wait before each additional note is started.
                Defaults to 0.05 seconds.
            volume: If not using Note instance(s), defines how loudly the notes will be played.
                Defaults to 0.25.
    '''
    if isinstance(length, str):
        raise Exception(
            "If you want to play multiple notes, wrap them in [] like playnotes(['C3', 'E3'])"
        )
    elif isinstance(length, Note):
        raise Exception(
            "If you want to play multiple notes, wrap them in [] like playnotes([note1, note2])"
        )

    if isinstance(namesOrNotes, str):
        namesOrNotes = [Note(namesOrNotes, length, delay, volume)]
    elif isinstance(namesOrNotes, Note):
        namesOrNotes = [namesOrNotes]
    elif isinstance(namesOrNotes[0], str):
        namesOrNotes = [
            Note(name, length, delay * index, volume)
            for index, name in enumerate(namesOrNotes)
        ]

    # Render all the notes.
    fullLength = 0.0
    sampleRate = 44100

    for note in namesOrNotes:
        fullLength = max(fullLength, note.length + note.delay)

    out = source.silence(fullLength +
                         0.1)  # Pad it a bit so I stop getting errors...
    #print('fullLength: {} silence samples: {}'.format(fullLength, len(out)))

    for note in namesOrNotes:
        firstSample = int(note.delay * sampleRate)
        #print('delay: {} first sample: {}'.format(note.delay, firstSample))
        data = note.render()
        #print('delay: {} first sample: {} data size: {}'.format(note.delay, firstSample, len(data)))
        out[firstSample:firstSample + len(data)] += data

    playback.play(out)
def play(data, volume=0.25) :
    # input is a proportion. 0<volume<1
    # example: a volume input of 0.25 makes it play at 25% volume

    # Reduce volume to the specified number
    data = data * volume

    # Playing the audio
    print "Playing the audio file..."
    playback.play(data)
示例#3
0
def organ_sound_test():
    """test playback with soundfont"""
    chords = [
        [50, 75, 100, 125, 150, 200, 250],
        [66.7, 84.4, 100, 112.5, 133.3, 200, 266.7],
        [75, 112.5, 133.3, 150, 190, 225],
    ]
    for chord in chords:
        data = sum(organ_sound(freq=note * 5, time=3) for note in chord)
        playback.play(data)
示例#4
0
        note = scale.get(random.randrange(4) * 2)
        note = note.at_octave(key.octave)
    else:
        # Transpose the note by some small random interval
        note = scale.transpose(note, random.choice((-2, -1, 1, 2)))
    length = random.choice((0.125, 0.125, 0.25))
    timeline.add(time, Hit(note, length + 0.125))
    time += length

# Resolve
note = scale.transpose(key, random.choice((-1, 1, 4)))
timeline.add(time, Hit(note, 0.75))  # Tension
timeline.add(time + 0.5, Hit(key, 4.0))  # Resolution

print("Rendering audio...")

data = timeline.render()

print("Applying chorus effect...")

data = effect.chorus(data, freq=3.14159)

# Reduce volume to 50%
data = data * 0.5

print("Playing audio...")

playback.play(data)

print("Done!")
示例#5
0
for index in [0, 2, 3, 1,    0, 2, 3, 4,    5, 4, 0]:
  chord = progression[index]
  root, third, fifth = chord.notes
  arpeggio = [root, third, fifth, third, root, third, fifth, third]
  for i, interval in enumerate(arpeggio):
    ts = float(i * 2) / len(arpeggio)
    timeline.add(time + ts, Hit(interval, 1.0))
  time += 2.0

# Strum out root chord to finish
chord = progression[0]
timeline.add(time + 0.0, Hit(chord.notes[0], 4.0))
timeline.add(time + 0.1, Hit(chord.notes[1], 4.0))
timeline.add(time + 0.2, Hit(chord.notes[2], 4.0))
timeline.add(time + 0.3, Hit(chord.notes[1].transpose(12), 4.0))
timeline.add(time + 0.4, Hit(chord.notes[2].transpose(12), 4.0))
timeline.add(time + 0.5, Hit(chord.notes[0].transpose(12), 4.0))

print "Rendering audio..."

data = timeline.render()

# Reduce volume to 25%
data = data * 0.25

print "Playing audio..."

playback.play(data)

print "Done!"
示例#6
0
def main(argv):
  try:
    opts, args = getopt.getopt(argv, "hdsm", ['help', 'debug', 'startup', 'morning'])
  except getopt.GetoptError:
    usage()
    sys.exit(2)

  global _debug
  _debug = 0

  morning = False 

  for opt, arg in opts:
    if opt in ("-h", "--help"):
      usage()
      sys.exit()

    if opt in ("-m", "--morning"):
      morning = True
      _debug = 1

    if opt == '-d':
      _debug = 1

    if opt in ("-s", "--startup"):
      import time
      time.sleep(90)
      #os.system("/usr/bin/tvservice -o")


  # Increase chance of singing at sunrise/sunset
  import ephem

  birdcage = ephem.Observer()
  birdcage.lat = '51.497517'
  birdcage.lon = '0.080380'
  birdcage.date = str(datetime.datetime.now())
  birdcage.elevation = 5

  sun = ephem.Sun()

  next_sunrise = birdcage.next_rising(sun)
  early_next_sunrise = ephem.Date(next_sunrise - 15 * ephem.minute) 
  late_next_sunrise = ephem.Date(next_sunrise + 15 * ephem.minute) 

  next_sunset = birdcage.next_setting(sun)
  early_next_sunset = ephem.Date(next_sunset - 15 * ephem.minute) 
  late_next_sunset = ephem.Date(next_sunset + 15 * ephem.minute) 

  sunrise = False;
  sunset = False;
  if (birdcage.date > early_next_sunrise and birdcage.date < late_next_sunrise):
    #print 'Sunrise roll'
    sunrise = true;
    dice_roll = random.choice([1,2,3,4,5,6,7,8])
  elif (birdcage.date > early_next_sunset and birdcage.date < late_next_sunset):
    #print 'Sunset roll'
    sunset = true;
    dice_roll = random.choice([1,2,3,4,5,6,7,8])
  else:
    dice_roll = random.choice([1,2,3,4,5,6])

  if (dice_roll < 5 and _debug <> 1):
    #print "Going back to sleep"
    sys.exit()

  # We're alive, import what else we need now
  sys.path.append(os.path.join(os.path.dirname(__file__), 'python-musical'))

  from musical.theory import Note, Scale, Chord
  from musical.audio import effect, playback

  from timeline import Hit, Timeline

  # Define key and scale
  key = Note((random.choice(Note.NOTES), random.choice([2,3,3])))

  scales = ['major', 'minor', 'melodicminor', 'harmonicminor', 'pentatonicmajor', 'bluesmajor', 'pentatonicminor', 'bluesminor', 'augmented', 'diminished', 'wholehalf', 'halfwhole', 'augmentedfifth', 'japanese', 'oriental', 'ionian', 'phrygian', 'lydian', 'mixolydian', 'aeolian', 'locrian']
  random.shuffle(scales)
  scale = Scale(key, random.choice(scales))

  #print key
  #print scale

  # Grab progression chords from scale starting at the octave of our key
  progression = Chord.progression(scale, base_octave=key.octave)

  time = 0.0 # Keep track of correct note placement time in seconds

  timeline = Timeline()

  # Pick a notes from a chord randomly chosen from a list of notes in this progression
  chord = progression[ random.choice(range(len(progression)-1)) ]
  notes = chord.notes

  melodies = [ 
    [0.8, 0.2],
    [0.4, 0.2],
    [0.2, 0.8],
    [0.2, 0.4],
    [0.6, 0.2],
    [0.4, 0.4, 0.2],
    [0.6, 0.1, 0.1],
    [0.8, 0.1, 0.2],
    [0.2, 0.2, 0.2],
    [0.2, 0.4, 0.2],
    [1.0, 0.1, 0.2, 0.1, 0.2, 0.10, 0.1],
    [0.8, 0.4, 0.1, 0.2, 0.4, 0.1, 0.2],
    [0.8, 0.4, 0.4, 0.2, 0.2, 0.1, 0.1],
    [0.4, 0.0, 0.1, 0.1, 0.2, 0, 0.1, 0.4],
    [0.1, 0.1, 0.1, 0.0, 0.2, 0.0, 0.1, 0.2, 0.4],
    [0.8, 0.4, 0.1, 0.4, 0.2, 0.2, 0.1, 0.2, 0.8, 0.1, 0.4, 0.1],
    [0.2, 0.2, 0.4, 0.2, 0.1, 0.1, 0.0, 0.2],
    [1.0, 0.1, 0.2, 0.1, 0.2, 0.2],
    [0.2, 0.1, 0.2, 0.4, 0.1, 0.2, 0.4],
    [0.4, 0.1, 0.4, 0.2, 0.4, 0.1, 0.4, 0.2],
    [0.1, 0.1, 0.1, 0.2, 0.1, 0.1, 0.2],
    [0.1, 0.1, 0.1, 0.2, 0.1, 0.1, 0.1, 0.2, 0.0],
    [0.1, 0.0, 0.1, 0.0, 0.1, 0.0, 0.2, 0.0, 0.2, 0.0, 0.1, 0.1, 0.3],
  ]

  if sunrise or sunset:
    random_melody = random.choice(melodies[0:12])
  else:
    random_melody = random.choice(melodies)

  # Testing a new melody-generation idea - duncan 11/4/20
  # - needs more work, disabling for now - 12/4/20
  #random_melody = []
  #melody_length = random.randrange(1, 12)
  #
  #for i in range(0, melody_length):
  #  random_melody.append( round(random.uniform(0.1, 0.6), 1) )
  # test end

  if morning:
    random_melody = melodies[-1]

  print random_melody

  last_interval = 0.0
  last_transpose = 0

  for i, interval in enumerate(random_melody):
    random_note = random.choice(notes)

    # the first note should be high
    # identical intervals should often hold the same pitch
    # otherwise, pick a random pitch
    if i == 0:
      random_transpose = random.choice([8, 12])
    elif (last_interval == interval):
      if random.choice([0,1,2]) == 2:
        random_transpose = last_transpose
      else:
        random_transpose = 0
    else:
      random_transpose = random.choice([0,2,4,6,8,10,12])

    last_interval = interval
    last_transpose = random_transpose

    note = random_note.transpose(random_transpose)
    #print note

    # favour queued notes, but occasionally overlap them too
    if (random.choice([1,2,3,4,5,6]) > 2):
      time = time + interval
      timeline.add(time, Hit(note, interval))
    else:
      timeline.add(time, Hit(note, interval))
      time = time + interval

  #print "Rendering audio..."
  data = timeline.render()

  # Reduce volume to 50%
  data = data * 0.5

  print "Playing audio..."
  if morning:
    for i in range(2):
      playback.play(data)
  else:
    for i in range(random.choice([1,2])):
      playback.play(data)
示例#7
0
def make_sound(type):
  mytimeline = Timeline()
  mytimeline.add(0, Hit(type, 1, sound_string[type]))
  data = mytimeline.render()
  playback.play(data)
示例#8
0
def play(data):
    playback.play(data)
示例#9
0
import pygame, urllib
from musical.audio import source, playback, effect

print 'Loading sound from internet...'

pygame.mixer.init()
rate, format, channels = pygame.mixer.get_init()
web = urllib.urlopen('http://www.moviesounds.com/matrix/dodge.wav')
sound = pygame.mixer.Sound(web)
data = source.pygamesound(sound)
pygame.mixer.quit()

print 'Applying flanger...'

data = effect.flanger(data, 1.0, dry=0.25, wet=0.75) * 0.75

print "Playing audio..."

playback.play(data, rate=rate)

print "Done!"
 def run(self):
     while not self.stopped.wait(0.001):
         playback.play(self.data)
示例#11
0
def main(argv):
  try:
    opts, args = getopt.getopt(argv, "hds", ['help', 'debug', 'startup'])
  except getopt.GetoptError:
    usage()
    sys.exit(2)

  global _debug
  _debug = 0
  for opt, arg in opts:
    if opt in ("-h", "--help"):
      usage()
      sys.exit()
    elif opt == '-d':
      _debug = 1
    elif opt in ("-s", "--startup"):
      import time
      time.sleep(90)
      os.system("/usr/bin/tvservice -o")
      _debug = 1
      

  # Increase chance of singing at sunrise/sunset
  import ephem

  birdcage = ephem.Observer()
  birdcage.lat = '51.5034070'
  birdcage.lon = '-0.1275920'
  birdcage.elevation = 19

  sun = ephem.Sun()

  next_sunrise = birdcage.next_rising(sun)
  early_next_sunrise = ephem.Date(next_sunrise - 15 * ephem.minute) 
  late_next_sunrise = ephem.Date(next_sunrise + 15 * ephem.minute) 

  next_sunset = birdcage.next_setting(sun)
  early_next_sunset = ephem.Date(next_sunset - 15 * ephem.minute) 
  late_next_sunset = ephem.Date(next_sunset + 15 * ephem.minute) 

  if (birdcage.date > early_next_sunrise and birdcage.date < late_next_sunrise):
    print 'Sunrise roll'
    dice_roll = random.choice([1,2,3,4,5])
  elif (birdcage.date > early_next_sunset and birdcage.date < late_next_sunset):
    print 'Sunset roll'
    dice_roll = random.choice([1,2,3,4,5])
  else:
    dice_roll = random.choice([1,2,3,4,5,6])

  if (dice_roll < 5 and _debug <> 1):
    print "Going back to sleep"
    sys.exit()

  # We're alive, import what else we need now
  sys.path.append(os.path.join(os.path.dirname(__file__), 'python-musical'))

  from musical.theory import Note, Scale, Chord
  from musical.audio import effect, playback

  from timeline import Hit, Timeline

  # Define key and scale
  key = Note((random.choice(Note.NOTES), random.choice([2,3,3])))

  scales = ['major', 'minor', 'melodicminor', 'harmonicminor', 'pentatonicmajor', 'bluesmajor', 'pentatonicminor', 'bluesminor', 'augmented', 'diminished', 'wholehalf', 'halfwhole', 'augmentedfifth', 'japanese', 'oriental', 'ionian', 'phrygian', 'lydian', 'mixolydian', 'aeolian', 'locrian']
  scale = Scale(key, random.choice(scales))

  print key
  print scale

  # Grab progression chords from scale starting at the octave of our key
  progression = Chord.progression(scale, base_octave=key.octave)

  time = 0.0 # Keep track of currect note placement time in seconds

  timeline = Timeline()

  # Pick a notes from a chord randomly chosen from a list of notes in this progression
  chord = progression[ random.choice(range(len(progression)-1)) ]
  notes = chord.notes

  melodies = [
    [1.0, 0.1, 0.2, 0.1, 0.2, 0.10, 0.1],
    [0.8, 0.1, 0.1, 0.2],
    [0.8, 0.4, 0.1, 0.2, 0.4, 0.1, 0.2],
    [0.8, 0.4, 0.4, 0.2, 0.2, 0.1, 0.1],
    [0.4, 0.0, 0.1, 0.1, 0.2, 0, 0.1, 0.4],
    [0.1, 0.1, 0.1, 0.0, 0.2, 0.0, 0.1, 0.2, 0.4],
    [0.8, 0.4, 0.1, 0.4, 0.2, 0.2, 0.1, 0.2, 0.8, 0.1, 0.4, 0.1],
    [0.2, 0.2, 0.4, 0.2, 0.1, 0.1, 0.0, 0.2],
    [1.0, 0.1, 0.2, 0.1, 0.2, 0.2],
    [0.2, 0.1, 0.2, 0.4, 0.1, 0.2, 0.4],
    [0.4, 0.1, 0.4, 0.2, 0.4, 0.1, 0.4, 0.2],
    [0.1, 0.1, 0.1, 0.2, 0.1, 0.1, 0.2],
    [0.1, 0.1, 0.1, 0.2, 0.1, 0.1, 0.1, 0.2, 0.0],
    [0.1, 0.0, 0.1, 0.0, 0.1, 0.0, 0.2, 0.0, 0.2, 0.0, 0.1, 0.1, 0.3],
  ]

  random_melody = random.choice(melodies)
  print random_melody

  last_interval = 0.0
  last_transpose = 0

  for i, interval in enumerate(random_melody):
    random_note = random.choice(notes)

    # the first note should be high
    # identical intervals should often hold the same pitch
    # otherwise, pick a random pitch
    if i == 0:
      random_transpose = random.choice([8, 12])
    elif (last_interval == interval):
      if random.choice([0,1,2]) == 2:
        random_transpose = last_transpose
      else:
        random_transpose = 0
    else:
      random_transpose = random.choice([0, 2,4,6,8,10,12])

    last_interval = interval
    last_transpose = random_transpose

    note = random_note.transpose(random_transpose)
    #print note

    # favour queued notes, but occasionally overlap them too
    if (random.choice([1,2,3,4,5,6]) > 2):
      time = time + interval
      timeline.add(time, Hit(note, interval))
    else:
      timeline.add(time, Hit(note, interval))
      time = time + interval

  print "Rendering audio..."
  data = timeline.render()

  # Reduce volume to 95%
  data = data * 0.95

  print "Playing audio..."
  for i in range(random.choice([1,2])):
    playback.play(data)

  print "Done!"