我怎么能创作旋律?有没有声响模块?

7 投票
4 回答
6958 浏览
提问于 2025-04-15 17:24

我有点困惑,因为有很多程序可供选择。但我想要的是这样的一个程序:我可以输入一个旋律,比如“a4 c3 h3 a2”等等,然后我想听到这个旋律。有没有人知道我在找什么?谢谢大家!

4 个回答

2

你可以使用任何能生成MIDI输出的库。如果你在用.net,我推荐微软的Stephen Toub创建的那个库(我找不到具体来源,但你可以在谷歌上搜索一下)。

3

一个外部选择是 JFugue,就像 这里展示的(使用Groovy语言)。请注意,你会使用 Jython 而不是Python,希望这能算作一个合适的答案。

8

从音符名称计算频率其实很简单。每个半音的频率相差是2的1/12次方,440赫兹对应的是A4音符。

如果你恰好在使用Windows系统,可以试试这段代码,它可以通过电脑的扬声器播放一首歌:

import math
import winsound
import time

labels = ['a','a#','b','c','c#','d','d#','e','f','f#','g','g#']
# name is the complete name of a note (label + octave). the parameter
# n is the number of half-tone from A4 (e.g. D#1 is -42, A3 is -12, A5 is 12)
name   = lambda n: labels[n%len(labels)] + str(int((n+(9+4*12))/12))
# the frequency of a note. the parameter n is the number of half-tones
# from a4, which has a frequency of 440Hz, and is our reference note.
freq   = lambda n: int(440*(math.pow(2,1/12)**n))

# a dictionnary associating note frequencies to note names
notes  = {name(n): freq(n) for n in range(-42,60)}

# the period expressed in second, computed from a tempo in bpm
period = lambda tempo: 1/(tempo/60)

# play each note in sequence through the PC speaker at the given tempo
def play(song, tempo):
    for note in song.lower().split():
        if note in notes.keys():
            winsound.Beep(notes[note], int(period(tempo)*1000))
        else:
            time.sleep(period(tempo))

# "au clair de la lune"!! 'r' is a rest
play( 'c4 c4 C4 d4 e4 r d4 r c4 e4 d4 d4 c4 r r r '
      'c4 C4 c4 d4 e4 r d4 r c4 e4 d4 d4 c4 r r r '
      'd4 d4 d4 d4 A3 r a3 r d4 c4 B3 a3 g3 r r r '
      'c4 c4 c4 d4 e4 r d4 r c4 e4 d4 d4 c4 r r r ', 180 )

(请注意,我使用的是Python 3.x,你可能需要对代码的某些部分进行调整,以便在Python 2.x上使用。)

哦,对了,我用abcdefg作为音阶,但你肯定能找到方法用h代替b

撰写回答