gpt4 book ai didi

python - 我怎样才能创作旋律?有声音模块吗?

转载 作者:太空狗 更新时间:2023-10-29 21:27:38 25 4
gpt4 key购买 nike

我很困惑,因为有很多程序。但我看起来像这样。我会输入一段旋律,例如“a4 c3 h3 a2”等,然后我想听听这个。有人知道我在找什么吗?提前致谢

最佳答案

根据音符名称计算频率很容易。每个半音符与前一个音符相距 2^(1/12),440 Hz 是 A4。

如果你碰巧在 Windows 上,你可以试试这段代码,它通过 PC 扬声器播放一首歌曲:

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 的方法.

关于python - 我怎样才能创作旋律?有声音模块吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1967040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com