TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Basic Music Theory in ~200 Lines of Python

451 点作者 mvanga大约 4 年前

34 条评论

WhompingWindows大约 4 年前
As a primer for music theory, this post doesn&#x27;t teach much. It&#x27;s using Python to derive various sets of notes in scales and modes, which is already easily available via google search, and in a more learnable format than Python code.<p>The most basic aspect of Western music theory overlooked here is the relationship between tonic and dominant. If you know the &quot;home&quot; chord aka &quot;the I&quot; aka &quot;tonic&quot; is C major, the dominant will be G major, aka the V chord. Add just the F major chord, and you&#x27;ll know 1-4-5 in a &quot;basic&quot; key: C major. 1-4-5 is the simplest chord progression, you can play amazing grace, you are my sunshine, even The Beatles, you&#x27;ll be rocking with 1-4-5.<p>Next level, if you add in the minor 6 (a minor) and minor 2 (d minor), you realistically know 95% of the chords you&#x27;ll ever hear in C major pieces. And on the piano, this is ALL white notes, so even someone with zero musical knowledge can &quot;solo&quot; over your chords by just plunking any white notes while you play these chords (kids LOVE LOVE this btw, highly recommend trying with a kiddo).<p>I wouldn&#x27;t consider double-sharps and double-flats &quot;basic&quot; music theory. They really aren&#x27;t needed for beginners, since they&#x27;re relegated to keys like C# major where you&#x27;ll occasionally sharpen a note like E# (aka F) into E## (aka F#). I didn&#x27;t run into these until around 5 years into my piano training, playing Chopin&#x27;s F# major nocturne Op 15 No 2, there&#x27;s a bunch of double sharps in that piece.<p>In any case, don&#x27;t worry about double-flats and double-sharps or the precise notes of various modes and scales. Just learn pieces you enjoy, preferably with a mentor or teacher who can suggest improvements based on their trained ear.
评论 #26863156 未加载
评论 #26866118 未加载
评论 #26867208 未加载
评论 #26868582 未加载
评论 #26866073 未加载
评论 #26867116 未加载
评论 #26865419 未加载
jancsika大约 4 年前
It can be tricky to deal with the intersection of music and programming. For example:<p>&gt; The chromatic scale is the easiest scale possible<p>So far so good-- in both programming and music we&#x27;re just stepping through the smallest values (half step for music, the integer &quot;1&quot; in programming). So &quot;easy&quot; definitely applies to both domains.<p>&gt; We can generate a chromatic scale for any given key very easily<p>For programming, sure-- you just find your offset and go to town.<p>For music, however, this is a wrong warp. The chromatic scale is a special case of a symmetric scale which cannot be transposed. There&#x27;s literally only one such scale-- each transposition brings you back to the same exact set of pitch classes.<p>Figuring out what it means to have a chromatic scale &quot;for a given key&quot; is advanced music theory. In fact, I can only think of a few places where that makes sense:<p>* studying the complex harmony of late-19th century Romantic music<p>* studying the choice of accidentals in chromatic passages of Bach, Beethoven, etc. to infer the implied harmony<p>Those are important things, but they are definitely advanced concepts.<p>Long story short for programming, the author moves logically from an array to stepping through an array. But in terms of music, they start with the simplest possible scale and then jump to a third year undergrad theory concept.
评论 #26862342 未加载
评论 #26863127 未加载
评论 #26863317 未加载
sampo大约 4 年前
There are maybe three aspects to music theory:<p>(1) Theory of how things sound like: Tones, melodies, scales, chords, based on the frequencies of individual sounds.<p>(2) How to name things.<p>(3) How to handle the mess of naming things in Western music theory, where things have 12 different names, depending on which note you choose as the base.<p>This post seems to focus on 3.
评论 #26861811 未加载
评论 #26862238 未加载
评论 #26863867 未加载
评论 #26863654 未加载
评论 #26861861 未加载
评论 #26864208 未加载
sideshowb大约 4 年前
Anyone wanting to take things back a step further to first principles may enjoy this (shameless plug - I wrote it)<p>Deriving the piano keyboard from biological principles using clustering (Jupyter)<p><a href="https:&#x2F;&#x2F;fiftysevendegreesofrad.github.io&#x2F;JupyterNotes&#x2F;piano.html" rel="nofollow">https:&#x2F;&#x2F;fiftysevendegreesofrad.github.io&#x2F;JupyterNotes&#x2F;piano....</a>
评论 #26860632 未加载
评论 #26861446 未加载
delineator大约 4 年前
Things get more fun when we explore musical tunings other than the 12 equal divisions of the octave (EDO) of Western music.<p>You can define interval structure as a sequence of large L, small s, and optionally medium M steps.<p>For example, the Major diatonic scale - a 7 note scale from 12 EDO - in Ls notation is:<p><pre><code> LLsLLLs with L: 2 s: 1 (12=2+2+1+2+2+2+1) </code></pre> A 19 EDO, 7 note scale:<p><pre><code> LLsLLLs with L: 3 s: 2 (19=3+3+2+3+3+3+2) </code></pre> And here&#x27;s a 19 EDO scale with 9 notes (Godzilla-9):<p><pre><code> LLsLsLsLsLs with L: 3 s: 1 (19=3+3+1+3+1+3+1+3+1) </code></pre> You can then explore frequency ratios beyond those available in 12 EDO: <a href="https:&#x2F;&#x2F;github.com&#x2F;robmckinnon&#x2F;pitfalls&#x2F;blob&#x2F;main&#x2F;lib&#x2F;ratios.lua" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;robmckinnon&#x2F;pitfalls&#x2F;blob&#x2F;main&#x2F;lib&#x2F;ratios...</a><p>And chords based on those ratios: <a href="https:&#x2F;&#x2F;github.com&#x2F;robmckinnon&#x2F;pitfalls&#x2F;blob&#x2F;main&#x2F;lib&#x2F;chords.lua" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;robmckinnon&#x2F;pitfalls&#x2F;blob&#x2F;main&#x2F;lib&#x2F;chords...</a><p>The above links are Lua code files for a monome norns library for exploring microtonal tuning: <a href="https:&#x2F;&#x2F;llllllll.co&#x2F;t&#x2F;pitfalls&#x2F;37795" rel="nofollow">https:&#x2F;&#x2F;llllllll.co&#x2F;t&#x2F;pitfalls&#x2F;37795</a>
algesten大约 4 年前
A perfect 5th is not the same as a diminished 6th unless we assume equal temperament tuning. Granted it is the dominant tuning, but it irks me when this is just silently assumed.<p>Plenty of music around that is recorded using actual perfect intervals, so why muddy the waters?
评论 #26862628 未加载
评论 #26862178 未加载
codeulike大约 4 年前
This is great but if we could go back in time and influence the naming conventions so that the 12 semitones were called A-L or just numbered 1 to 12, and if the intervals were named after the actual semitone distance (a &#x27;fifth&#x27; is actually seven semitones) the whole thing would be soooo much less jargonny. With all that bumf removed, the patterns of the &#x27;scales&#x27; and &#x27;chords&#x27; would be foregrounded and thats the actually interesting bit IMHO (the bit defined as &#x27;formulas = {..}&#x27; in the article)
评论 #26861915 未加载
评论 #26861482 未加载
评论 #26861312 未加载
评论 #26860856 未加载
评论 #26860860 未加载
评论 #26861316 未加载
protoman3000大约 4 年前
&gt; Modes are essentially left-rotations of a scale.<p>While true, I find this interpretation harmful to the understanding of modes. It didn&#x27;t provide me with any insight and instead it seemed irregular to the other theoretical constructs we have and thus deterred and misled me in the beginning.<p>To me, it all clicked when I took all the modes, except Lydian, and constructed them by putting down the augmentations to the major scale in a circle-of-fifths sorted way:<p>Mixolydian: b7, Dorian: b7 b3, Aeolian: b7 b3 b6, ...<p>You can see that the modes appear walking left on the circle of fifths or walking along fourths (or going &quot;darker&quot;, as some prefer to say). Try this out when starting at e.g. C and you see the pattern immediately.<p>Then take Lydian: #4<p>That&#x27;s going right on the circle of fifths or going in fifths going &quot;brighter&quot;.<p>Also, tangential comment: My music and my life has changed profoundly when I found out how to use the Lydian mode. I can&#x27;t explain it, but it is just exciting.
评论 #26863313 未加载
评论 #26864880 未加载
评论 #26860664 未加载
HorkHunter大约 4 年前
Does any programmer suffer with music theory as well, just based on the fact that an exact thing could be called in many different ways, depends on its position, function..etc?<p>my brain kind of cannot accept this fact and I struggle with it
评论 #26862316 未加载
评论 #26862300 未加载
评论 #26862312 未加载
pohl大约 4 年前
A fun idea for a function to implement: the negative harmony mapping, which is a note-by-note transformation that preserves some character of the note:<p><pre><code> R ⟷ 5 (stable) 2 ⟷ 4 (unstable) 3 ⟷ ♭3 (modal) 7 ⟷ ♭6 (leading) 6 ⟷♭7 (hollow) ♭2 ⟷ ♯4 (uncanny) [1] https:&#x2F;&#x2F;www.youtube.com&#x2F;watch?v=et3CMn2oCsA [2] https:&#x2F;&#x2F;www.youtube.com&#x2F;watch?v=SF8CdxcdJgw</code></pre>
goto11大约 4 年前
&gt; For historical reasons, there are no sharps or flats between the notes B&#x2F;C, and E&#x2F;F.<p>Come on, that is not for &quot;historical reasons&quot;, that is because those notes are only one semitone apart!
评论 #26861996 未加载
评论 #26862017 未加载
whiddershins大约 4 年前
“ For historical reasons, there are no sharps or flats between the notes B&#x2F;C, and E&#x2F;F.”<p>Mmmm yes, and that’s also a bit confusing because it dodges around why the scale was and is 7 notes to begin with.
评论 #26860594 未加载
评论 #26862553 未加载
pashariger大约 4 年前
I found this very helpful! As a self-taught musician, it filled some gaps in my music theory knowledge - especially being able to visualize computing scales, modes, and intervals as algorithms. I can now better evaluate these in my head when I encounter a key&#x2F;scale that I haven&#x27;t seen before! Thank you!
calebm大约 4 年前
I have some similar notes here: <a href="https:&#x2F;&#x2F;calebmadrigal.com&#x2F;music-theory-notes&#x2F;" rel="nofollow">https:&#x2F;&#x2F;calebmadrigal.com&#x2F;music-theory-notes&#x2F;</a>. It&#x27;s all about the ratios.
dvfjsdhgfv大约 4 年前
It would be awesome to add short audio clips. I mean, the examples are correct and all, but it&#x27;s like discussing painting or photography without a single picture.
评论 #26862082 未加载
bdenckla大约 4 年前
This is a fun read but IMO it falls into the common trap of trying to formalize concepts in music theory based on a representation too close to traditional music notation. A notable consequence of this trap is that the author has to do a lot of distracting work to handle enharmonics, and yet still has arbitrary limits on number of flats and sharps. In other words, he has to do a lot of distracting work, and still all that work doesn&#x27;t yield a general system.<p>In my opinion (and experience) it is better to do a little work &quot;up front&quot; and &quot;in the back&quot; to convert to the line-of-fifths representation since that is more friendly to formalization. In other words you can take input in traditional musical notation and give output in traditional musical notation, but &quot;in the middle,&quot; formalization should be done in the line-of-fifths representation.<p>Above I have used &quot;formalize&quot; to mean something like &quot;mathematicize&quot; (if that&#x27;s a word) or &quot;be precise&quot; or &quot;be able to compute&quot; or &quot;be able to express in a programming language (like Python)&quot;. For example, I consider the line-of-fifths representation to be a good one in which to formalize music theory because in line-of-fifths representation, transposition can simply be formalized as integer addition, and integer addition needs no further explanation or formalization, i.e. it can be taken as sort of axiomatic.<p>Here&#x27;s another way of putting it: if you wanted to be able to add Roman numeral strings, would you write code that directly operated on the Roman numeral strings, or would you first convert to a compute-friendly representation like integers, and then do your adding from there? No doubt there are tradeoffs involved, but I tend to think that it is usually worth it to move to a compute-friendly representation, both with Roman numerals and music notation.<p>An added benefit of line-of-fifths representation is it provides a good basis to formalize many important historical European tuning systems.
peterpostman大约 4 年前
Unreadable code,considering the subject should have been written in either in c, c#, d, f or f#.
评论 #26862423 未加载
FabHK大约 4 年前
I haven&#x27;t found an introduction to music theory that makes sense to me.<p>I vaguely understand that complications arise because we want nice harmonics, ie frequencies whose ratio is a &quot;nice&quot; rational number, such as 2&#x2F;3 or 3&#x2F;5 or so.<p>But our chosen notes should be invariant under doubling of frequencies (&quot;shifting by an octave&quot;), because that&#x27;s basically the same note.<p>The problem then is that roots of 2 are irrational, that is, one cannot find (p&#x2F;q)^2 = 2, or (p&#x2F;q)^n = 2, or even (p&#x2F;q)^n = 2^m. Therefore, one cannot find a &quot;nice&quot; interval that, applied several times, wraps around to an octave (or multiple octaves).<p>However, in a neat coincidence, (3&#x2F;2)^12 = 129.7463378906... which is close to 2^7 = 128. So, based on that (&quot;Pythagorean comma&quot;), something something something, and we end up with 12 half notes that are basically of frequency f_i = f_0 * 2^(i&#x2F;12), which are all horribly irrational, but apparently sound &quot;nice&quot; enough, largely (because they are close enough to some &quot;nice&quot; fractions), but only if we pick out some specific 7 of them.<p>And then the question becomes, which 7 of the 12 do we pick, approximately uniformly distributed. (Why not 6? Every second? I don&#x27;t know.)<p>And then, you can transpose them somehow (ie multiply frequencies by 2^(j&#x2F;12) for some j, but then you change the names for some reason, and everything gets complicated and tonic and Mixolidian double-sharp.<p>Also, instead of frequencies of the form f_i = f_0 * 2^(i&#x2F;12) (which, clearly, have the advantage that any multiplication by a power of 2^(1&#x2F;12) is just a shifting of the index i), you could also use non-equal tuning, with the powers of the 12th root of 2 replaced by some &quot;nice&quot; fraction, which means that any shifting then subtly changes the character of everything, I assume.<p>This is complicated, admittedly, but for me the nomenclature obscures, rather than elucidates, the issue.<p>ETA: I sympathise with what <i>irrational</i> wrote: &quot;Is this what it is like when I talk to people who don’t know anything about programming about my work? Pure gibberish?&quot;
评论 #26868202 未加载
geekster777大约 4 年前
Something I wish was more clear in music theory is just how much overlap exists between the various concepts. I think it suffers from having so many names for everything, the learning curve seems much steeper than it really is. Even in this article, much time is spent on the duplicate names of notes and intervals. As a fairly proficient self-taught guitarist, this intimidating perception of theory delayed my learning of it for easily 5-8 years.<p>For example, you may spend a while learning the major scale, and what can be done with it. Then you learn the minor scale, and it seems like a totally separate scale that sounds completely different. And after that you learn that there are five other scales (modes) to learn about! (Dorian, Phrygian, Lydian, Mixolydian, and Lochrian!). It can seem extremely overwhelming until you learn that they&#x27;re all the same scale with different relative starting positions. Where major is [1,2,3,4,5,6,7], minor is [6,7,1,2,3,4,5], and the other modes are all the other permutations of starting positions.<p>My other gripe is that learning theory on piano puts a lot of bias on the notes themselves rather than the intervals. For example, the B major scale has 5 sharp notes (black keys) to remember whereas C major scale has none. These are pretty different shapes to remember. Learning these on guitar means taking the same exact shape and shifting it up a fret (so if you know one major scale, you know them all!). Not to say that guitar is the perfect instrument for learning this - folks will often learn scales as close to the 0th fret as possible, causing you to start on different strings and have slightly different patterns.<p>That being said, I wish there was a purely linear instrument (a piano with the black keys flattened?) for learning theory. The real magic comes from identifying the shapes and patterns, and how they&#x27;re similar to each other. Like how major and mixolydian are identical except for one note, so it&#x27;s very easy to modulate between them, or make a listener think they&#x27;re in one mode when they&#x27;re in another. Same with minor and phrygian. Being able to drop the baggage of &quot;the second note of the B major scale is C# which is this black key here&quot; and just focus on a floating set of intervals seems like it would make this all easier and less intimidating.<p>That all said, I still feel reasonably early in my theory journey. So maybe this is just my bias coming from guitar.
ngcc_hk大约 4 年前
Notation wise and officially it is a loop. But the tuning is a compromise. Hence some sounds are not harmonised that way using the current scale. There is a reason why well-tempered clavier tuning is still a bit of debate. You may have to tune fir some songs differently in those days. Hence assume all flat and sharp are equal is a bit too pure that might not exist n the real world.
valdiorn大约 4 年前
Hi there - was wondering if you had come across my Pentatonic scale github repo by any chance? :) It&#x27;s a very similar type of study, where I attempted to generate all possible pentatonic scales (within reason).<p><a href="https:&#x2F;&#x2F;github.com&#x2F;ValdemarOrn&#x2F;PentatonicScales" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;ValdemarOrn&#x2F;PentatonicScales</a>
markc大约 4 年前
Overtone is a music toolkit in Clojure. One of its source modules similarly captures music theory:<p><a href="https:&#x2F;&#x2F;github.com&#x2F;overtone&#x2F;overtone&#x2F;blob&#x2F;master&#x2F;src&#x2F;overtone&#x2F;music&#x2F;pitch.clj" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;overtone&#x2F;overtone&#x2F;blob&#x2F;master&#x2F;src&#x2F;overton...</a>
njharman大约 4 年前
We need more &quot;Explain things like I&#x27;m a programmer&quot; explanations.<p>I&#x27;ve tried to grok music theory several times. I&#x27;ve never understood the scale&#x2F;notes, notations. The 2nd array (with sharps and flats) and couple paragraphs made it &quot;click&quot; instantly. Because it was in a language and presentation I understand.
dvh大约 4 年前
Not a musician here but are scales really necessary? Why not just play any frequency I want?
评论 #26864153 未加载
评论 #26862845 未加载
评论 #26868633 未加载
评论 #26862533 未加载
评论 #26862545 未加载
评论 #26868630 未加载
diegoperini大约 4 年前
I wonder if there is a scripting environment where I describe a chord progression in one thread, a lead voice in another and run them simultaneously, written entirely in code as a single file (or 2 files for parts + 1 for importing those).
评论 #26860510 未加载
评论 #26862651 未加载
muyanapar大约 4 年前
Love this article, i really enjoyed reading the code and now i want to reproduce it.
starchild_3001大约 4 年前
I thought this is very cute. Playing these as chords or arpeggios, then adding other features to put them together to form a melody or chord progression, then hearing the effects would be super cool.
noisem4ker大约 4 年前
Perhaps related:<p>Haskell School of Music <a href="http:&#x2F;&#x2F;www.euterpea.com&#x2F;haskell-school-of-music&#x2F;" rel="nofollow">http:&#x2F;&#x2F;www.euterpea.com&#x2F;haskell-school-of-music&#x2F;</a>
keymasta大约 4 年前
I&#x27;ve worked on music theory coding for a while. I originally used a dict-lookup style like you have done, but found a simpler way (for me). The problem with that approach is you have to maintain values for enharmonics of note names. It&#x27;s hardwired. Also what if you gave it something like ♭♭♭♭♭♭44? Why shouldn&#x27;t it &quot;theoretically&quot; be able to handle that. It is &quot;theory&quot; after all. I use something like this to convert things basically to an int (if we want to for some other function):<p><pre><code> # Assuming note values are of Jazz style.. i.e, &#x27;1&#x27;, &#x27;b3&#x27;, &#x27;#5&#x27;, or &#x27;♭3&#x27; with unicode-sub after jazzAllFlats = [&#x27;1&#x27;,&#x27;b2&#x27;,&#x27;2&#x27;,&#x27;b3&#x27;,&#x27;3&#x27;,&#x27;4&#x27;,&#x27;b5&#x27;,&#x27;5&#x27;,&#x27;b6&#x27;,&#x27;6&#x27;,&#x27;b7&#x27;,&#x27;7&#x27;] sharpStrs = [&#x27;#&#x27;,&#x27;♯&#x27;] flatStrs = [&#x27;b&#x27;,&#x27;♭&#x27;] accidentalStrs = sharpStrs + flatStrs def stripAccidentals(note:str) -&gt; str: return &#x27;&#x27;.join([c for c in note if not c in accidentalStrs]) def jazzToDist(jazz:str) -&gt; int: dist = 0 degree = int(stripAccidentals(jazz)) while degree &gt; 7: dist += 12 degree -= 7 dist += jazzAllFlats.index(str(degree)) for c in jazz: if c in sharpStrs: dist += 1 elif c in flatStrs: dist -= 1 #Here you could add support for double sharps and double flats if you want.. although unlikely as font support for these glyphs is horrible overall. else: break return dist print(jazzToDist(&#x27;bb3&#x27;)) # returns 2 print(jazzToDist(&#x27;1&#x27;)) # returns 0 print(jazzToDist(&#x27;♭♭♭♭♭♭44&#x27;)) # returns 68 print(jazzToDist(&#x27;2&#x27;)) # This one is strange as it&#x27;s the only one where input == output </code></pre> I started making stuff more like this as it just saves a lot of trouble in the long run. Once you have things made generic like these it&#x27;s easier to think about going into ways that are not Jazz&#x2F;Dist (which is semitone distance, or set notation), like Keys for example.. because it turns out the logic for that is really similar to what is in the jazz.<p>The shape of the jazz system is the same shape as a change in the key of C. You would just separate the accidental part of the note&#x27;s name like I did and look up let&#x27;s say the index in all keys, giving you distance from C instead of what I showed there which is like distance from what is called 1 in Jazz.<p>So yes I prefer to make helper functions like this that actually kind of &quot;get it&quot; about what the languages&#x2F;ways like Jazz or note names are actually saying.. then you can go one to another, or different keys really easily. If interested in more of my &quot;Way Of Change&quot; algorithms I can share.<p>I think your article is cool and I could comment more.. maybe if you want you could read my repo I could pm it to you. But it&#x27;s long. In the meantime I have a new website using some of this type of logic. unfortunately js instead of python (where my bigger codebase resides).<p>Google thinks this site is a security threat and I literally posted it two days ago but it&#x27;s got all scales&#x2F;chords etc, and other stuff. Still in prototype phase. <a href="https:&#x2F;&#x2F;edrihan.neocities.org&#x2F;wayofchange%20v14.html" rel="nofollow">https:&#x2F;&#x2F;edrihan.neocities.org&#x2F;wayofchange%20v14.html</a>
评论 #26863410 未加载
评论 #26861231 未加载
tarboreus大约 4 年前
Is there a (really) accessible book on music theory that anyone would recommend?
评论 #26868709 未加载
评论 #26863998 未加载
adamnemecek大约 4 年前
I&#x27;ve been working on an IDE for music composition and I like to think that I nailed the UI.<p>Launching soon <a href="http:&#x2F;&#x2F;ngrid.io" rel="nofollow">http:&#x2F;&#x2F;ngrid.io</a>.
tomrod大约 4 年前
I love this!
vram22大约 4 年前
Apropos, some years ago I had written this blog post and Python program:<p>Play the piano on your computer with Python:<p><a href="https:&#x2F;&#x2F;jugad2.blogspot.com&#x2F;2013&#x2F;04&#x2F;play-piano-on-your-computer-with-python.html?m=0" rel="nofollow">https:&#x2F;&#x2F;jugad2.blogspot.com&#x2F;2013&#x2F;04&#x2F;play-piano-on-your-compu...</a><p>The post got some interesting comments with info about Western music theory, which I knew nothing about. And suggestions on how to improve the program to make calculation of note frequencies more accurate.
fatiherikli大约 4 年前
lop