2783030 0

 

Project Progressing... 

from music21 import note, stream
from decorators import get_halftones, get_basenote
from random import randint


# 把作曲的N多方法封为一类
class Compose():
    # 初始化
    def __init__ (self):
        self.music = []
        self.time_signature = [4,4]
        numerator = self.time_signature[0]
        denominator = self.time_signature[1]
        self.default_bar_QL = numerator / denominator * 4 
        self.key_signature = 'C_maj'
        self.tempo = 88
 
    # 随机作曲方法,装饰器get_halftones会把不是数字的音乐范围转化为数字
    @get_halftones
    @get_basenote
    def random_bars (self, **kw):
        # 实例变量赋值
        self.music_length = kw['music_length']
        self.base_note = kw['base_note']
        self.compose_range = kw['compose_range']

        # 逐个小节生成音符
        for i in range(self.music_length):
            self.music.append([])

            # 生成当前小节的音符数量
            note_num = randint(1,8)
            
            # 计算每小节的 QL
            

            # 生成每个音符
            for j in range(note_num):
                # 生成音高
                note_pitch = self.base_note + randint(-self.compose_range, self.compose_range)
                self.music[i].append(note_pitch)

                # 生成本音符的 QL
                pass

    # 这个方法可以创建一个小节的随机节奏型
    # (self, 音符数量, 小节长度, 最小时值, 占空比, )
    def rand_rhythm(self, note_num, QL_bar, duty_cycle):
        # 有音符和没音符的长度
        beat_QL = QL_bar * duty_cycle
        rest_QL = QL_bar - beat_QL
        # 检查参数是否合理
        

        # 初始化节奏型,每个音符初始为1QL,音符数量符合要求,调节音符长度
        beat_list = [1] * note_num

        while abs(sum(beat_list) - beat_QL) > 0.25:
            # 在节奏列表里获取随机索引
            rand_index = randint(0, len(beat_list) - 1)

            # 如果小节总音值小于要求,随机选一音符减半
            if sum(beat_list) < beat_QL:
                # 分裂那个随机音符,如果它的时值足够1/2拍
                if beat_list[rand_index] < beat_QL / 2:
                    beat_list[rand_index] *= 2
            # 如果小节总音质超出要求,随机增倍一音符
            else:
                if beat_list[rand_index] >= 1/2:
                    beat_list[rand_index] *= 0.5

        self.beat_list = beat_list.copy()


# 实例化
compose1 = Compose()
# 调用实例方法 随机作曲
compose1.random_bars(music_length = 10, base_note = "G#4", compose_range = "min_6")
# 打印生成的音乐
print(compose1.music_length, compose1.base_note, compose1.compose_range)
print(compose1.music)
# print(compose1.music)
compose1.rand_rhythm(5, 4, 0.5)
print(compose1.beat_list)

 


Share with friends on:

Follow Jake on:

Related articles