The Math of Music

Questions about programming languages and debugging
Post Reply
User avatar
maboroshi
Dr. Mab
Dr. Mab
Posts: 1624
Joined: 28 Aug 2005, 16:00
18

The Math of Music

Post by maboroshi »

Thought this was kind of neat came across a script using Math to create a Musical note

Code: Select all

import math
import struct
import pyaudio

def play_tone(frequency, amplitude, duration, fs, stream):
    N = int(fs / frequency)
    T = int(frequency * duration)  # repeat for T cycles
    dt = 1.0 / fs
    # 1 cycle
    tone = (amplitude * math.sin(2 * math.pi * frequency * n * dt)
            for n in xrange(N))
    # todo: get the format from the stream; this assumes Float32
    data = ''.join(struct.pack('f', samp) for samp in tone)
    for n in xrange(T):
        stream.write(data)

fs = 48000
p = pyaudio.PyAudio()
stream = p.open(
    format=pyaudio.paFloat32,
    channels=1,
    rate=fs,
    output=True)

# play the C major scale
scale = [130.8, 146.8, 164.8, 174.6, 195.0, 220.0, 246.9, 261.6]
for tone in scale:
    play_tone(tone, 0.5, 0.75, fs, stream)

# up an octave
for tone in scale[1:]:
    play_tone(2*tone, 0.5, 0.75, fs, stream)

stream.close()
p.terminate()

User avatar
ayu
Staff
Staff
Posts: 8109
Joined: 27 Aug 2005, 16:00
18
Contact:

Re: The Math of Music

Post by ayu »

ah neat xD
"The best place to hide a tree, is in a forest"

User avatar
joebox
Fame ! Where are the chicks?!
Fame ! Where are the chicks?!
Posts: 213
Joined: 19 Mar 2012, 18:15
12
Contact:

Re: The Math of Music

Post by joebox »

nice what code is that?
Award winning Unlimited Web Hosting
$1.81/month http://www.topratedhostservice.com
3 free domains | $100.00 Free advertising credits | Free Custom website design
Image

User avatar
ayu
Staff
Staff
Posts: 8109
Joined: 27 Aug 2005, 16:00
18
Contact:

Re: The Math of Music

Post by ayu »

joebox wrote:nice what code is that?
It's Python
"The best place to hide a tree, is in a forest"

User avatar
computathug
Administrator
Administrator
Posts: 2693
Joined: 29 Mar 2007, 16:00
17
Location: UK
Contact:

Re: The Math of Music

Post by computathug »

I remember creating my first tune on the spectrum in basic in similar way *thumb*

No old man jokes needed :lol:
The devil can cite Scripture for his purpose.
-- William Shakespeare, "The Merchant of Venice"
https://tshirt-memes.com

User avatar
ph0bYx
Staff Member
Staff Member
Posts: 2039
Joined: 22 Sep 2008, 16:00
15
Contact:

Re: The Math of Music

Post by ph0bYx »

I actually did that too, thugz! I'm not old, I guess..

User avatar
lilrofl
Siliconoclast
Siliconoclast
Posts: 1363
Joined: 28 Jan 2009, 17:00
15
Location: California, USA
Contact:

Re: The Math of Music

Post by lilrofl »

That's pretty neat Mabs, don't forget that MIDI is also music by math in binary.
knuffeltjes voor mijn knuffel
[img]http://i911.photobucket.com/albums/ac320/stuphsack/Sig.jpg[/img]

Post Reply