SlideShare une entreprise Scribd logo
1  sur  96
Télécharger pour lire hors ligne
noise.rb
How to annoy your cat with sound generators




Arlington Ruby, May 2012
Brock Wilcox
awwaiid@thelackthereof.org
Let's build a software synthesizer
in about 20 40 minutes.
Digital Sound
Exercises for reader:

Speakers → Ears → Consciousness
Let's start with speakers
Sideways is even better
Alternating Current
Sound = Speaker movement = Electrical input
Waves
digital?
Divide into samples
A sample is number from -1 .. 1
(y-axis)
Evenly spaced over time
(x-axis)
Samples per second

↳ "Sample Rate"
Common sample rates:

DVD: 48,000
CD: 44,100
VOIP: 16,000
Telephone: 8,000
Representation of each sample

↳ "Bit Depth"
8 bit: 0..255 (old video games)

16 bit: 0..65535 (CD)

24 bit: 0..16777215 (DVD-Audio)
Human Ear: 21 bit @ 40k
Volume (amplitude) and Frequency
Volume is easy!
Frequency not so easy
frequency = wiggle speed = pitch
Low bit depth
causes volume-aliasing
Low sample rate
causes frequency-aliasing
So!
We just gotta generate and play samples!
44100 of them per second!
No problem.
PortAudio
Alternatives: /dev/dsp, aplay, ...
PortAudio.init

stream = PortAudio::Stream.open(
  :sample_rate => 44100,
  :frames      => 512,
  :output      => {
    :device         => PortAudio::Device.default_output,
    :channels       => 1,
    :sample_format => :float32
  }
)

stream.start
buffer = PortAudio::SampleBuffer.new(
  :format   => :float32,
  :channels => 1,
  :frames   => 512
)
# smallnoise.rb

loop do
  buffer.fill {
    rand()*2 - 1 # From -1 .. 1
  }
  stream << buffer
end
Woo... static!
sample = rand()*2 - 1
# smallbeep.rb

time_step = 1 / 48000.0
time = 0.0
loop do
  buffer.fill {
    time += time_step;
    Math.sin( 2 * 3.1415 * time * 440 );
  }
  stream << buffer
end
Woo... beeping!
Two beeps at once?
Turns out you just add waves together
# smallbeep2.rb

sample = Math.sin( 2 * 3.1415 * time * 440 );
sample += Math.sin( 2 * 3.1415 * time * 349.23 );
sample /= 2; # Avoid clipping!
Let's generalize
sample = get_next_sample();
Call get_next_sample() over and over
Get a new sample each time
def sine {
  Math.sin( 2 * 3.1415 * $time * 440 )
}
That was easy.
Not very configurable or dynamic though.
# What I want:

sample_gen = sine(440);

# ...

sample = sample_gen.call;
This is called a 'generator'
We can make this using a closure!
(aka lambda with bound variables)
def sine(freq)
  lambda {
    Math.sin( 2 * 3.1415 * $time * freq );
  }
}
# So now we have it:

sample_gen = sine(440);

# ... in 'play'

sample = sample_gen.call;
# Create a 440 Hz sine generator
gen = sine(440);

# Play it!
play( gen );
play( sine( 440 ) );
One more generator tweak
Parameterize generators with generators,
and use named params
sub sine(freq) {
  freq = genize freq
  lambda {
    Math.sin( 2 * 3.1415 * $time * freq.call );
  }
}
# Take a parameter and ensure it is a generator.
# If it is already a generator leave it alone,
# otherwise wrap it up so that it *is* a generator.

def genize x
  if x.is_a?(Proc)
    return x
  end
  lambda { x }
end
Why would we use generators
as parameters?
lfo = sine(5)
wobble_freq = lambda { lfo.call * 100 + 440 }

play( sine( wobble_freq ) );
Now we're cooking with FIRE!
Plays forever...
Envelope Generator
Attack, [Decay], Sustain, Release
envelope( gen, attack, sustain, release )

# For example

envelope( sine(440), 2, 0, 2 )
returns nil when done
Sequence Generator
seq( gens )

# For example

play(
  seq([
     envelope(square(440), 2, 0, 2),
     envelope(square(220), 2, 0, 2),
  ])
)
Simultaneous Generators Generator
play(
  sum([
     envelope(square(440),   2,   0,   2),
     envelope(square(220),   2,   0,   2),
     envelope(square(880),   2,   0,   2),
     envelope(square(660),   2,   0,   2),
  ])
)
Let's build something we can PLAY
Input Control Generator
Using my touch-screen
$ xmousepos
838 574 221 170
x = `xmousepos`.split[0];
def mousefreq()
  count = 0
  x = 0.0
  lambda {
    count += 1
    if count % 1000 == 0
      x = `xmousepos`.split[0].to_f
    end
    x
  }
end
play(
   amp(
     sine( mousefreq() ),
     mousevol()
   )
);
And now we have a synth :)
THE END
References

Source Code:
http://thelackthereof.org/NoiseGen
http://github.com/awwaiid/ruby-noise

Digital fidelity discussion:
http://people.xiph.org/~xiphmont/demo/neil-young.html
BONUS SLIDES
Note / Song Generators
note( 'A4' )
segment( 'A4 F3' ),
combine([
   segment( 'A4' ),
   segment( 'F3' ),
])
Formula-Based Noise
http://countercomplex.blogspot.com/2011/10/algorithmic-symphonies-from-one-line-of.html

Contenu connexe

Tendances

Distributed Data Structures
Distributed Data StructuresDistributed Data Structures
Distributed Data Structures
PDX Web & Design
 
Sound generating
Sound generatingSound generating
Sound generating
LewisB2013
 

Tendances (14)

DSC - Android Study Jams - Session 2
DSC - Android Study Jams - Session 2 DSC - Android Study Jams - Session 2
DSC - Android Study Jams - Session 2
 
Distributed Data Structures
Distributed Data StructuresDistributed Data Structures
Distributed Data Structures
 
2013 0928 programming by cuda
2013 0928 programming by cuda2013 0928 programming by cuda
2013 0928 programming by cuda
 
Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02
 
Sample Jarvis(desktop assistant)
Sample Jarvis(desktop assistant)Sample Jarvis(desktop assistant)
Sample Jarvis(desktop assistant)
 
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + ProcessingRoberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
 
Atari 2600 Programming for Fun
Atari 2600 Programming for FunAtari 2600 Programming for Fun
Atari 2600 Programming for Fun
 
SuperCollider SS2016 5
SuperCollider SS2016 5SuperCollider SS2016 5
SuperCollider SS2016 5
 
Un monde où 1 ms vaut 100 M€ - Devoxx France 2015
Un monde où 1 ms vaut 100 M€ - Devoxx France 2015Un monde où 1 ms vaut 100 M€ - Devoxx France 2015
Un monde où 1 ms vaut 100 M€ - Devoxx France 2015
 
ubunturef
ubunturefubunturef
ubunturef
 
The Ring programming language version 1.9 book - Part 56 of 210
The Ring programming language version 1.9 book - Part 56 of 210The Ring programming language version 1.9 book - Part 56 of 210
The Ring programming language version 1.9 book - Part 56 of 210
 
Tensorflow + Keras & Open AI Gym
Tensorflow + Keras & Open AI GymTensorflow + Keras & Open AI Gym
Tensorflow + Keras & Open AI Gym
 
Sound generating
Sound generatingSound generating
Sound generating
 
Js hacks
Js hacksJs hacks
Js hacks
 

Similaire à NoiseGen at Arlington Ruby 2012

A Bizarre Way to do Real-Time Lighting
A Bizarre Way to do Real-Time LightingA Bizarre Way to do Real-Time Lighting
A Bizarre Way to do Real-Time Lighting
Steven Tovey
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the point
seanmcq
 

Similaire à NoiseGen at Arlington Ruby 2012 (20)

Digital signal processing through speech, hearing, and Python
Digital signal processing through speech, hearing, and PythonDigital signal processing through speech, hearing, and Python
Digital signal processing through speech, hearing, and Python
 
Music as data
Music as dataMusic as data
Music as data
 
Audio DSP in ReasonML
Audio DSP in ReasonMLAudio DSP in ReasonML
Audio DSP in ReasonML
 
How to tune Kafka® for production
How to tune Kafka® for productionHow to tune Kafka® for production
How to tune Kafka® for production
 
"Elixir of Life" - Dev In Santos
"Elixir of Life" - Dev In Santos"Elixir of Life" - Dev In Santos
"Elixir of Life" - Dev In Santos
 
Session3
Session3Session3
Session3
 
Erlang bootstrap course
Erlang bootstrap courseErlang bootstrap course
Erlang bootstrap course
 
Audio Data Representation (NCGD009)
Audio Data Representation (NCGD009)Audio Data Representation (NCGD009)
Audio Data Representation (NCGD009)
 
A Bizarre Way to do Real-Time Lighting
A Bizarre Way to do Real-Time LightingA Bizarre Way to do Real-Time Lighting
A Bizarre Way to do Real-Time Lighting
 
Using Python3 to Build a Cloud Computing Service for my Superboard II
Using Python3 to Build a Cloud Computing Service for my Superboard IIUsing Python3 to Build a Cloud Computing Service for my Superboard II
Using Python3 to Build a Cloud Computing Service for my Superboard II
 
Ruby 1.9
Ruby 1.9Ruby 1.9
Ruby 1.9
 
DomCode 2015 - Abusing phones to make the internet of things
DomCode 2015 - Abusing phones to make the internet of thingsDomCode 2015 - Abusing phones to make the internet of things
DomCode 2015 - Abusing phones to make the internet of things
 
Python meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OPython meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/O
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
 
JVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in Kotlin
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the point
 
Fourier project presentation
Fourier project  presentationFourier project  presentation
Fourier project presentation
 
NTU ML TENSORFLOW
NTU ML TENSORFLOWNTU ML TENSORFLOW
NTU ML TENSORFLOW
 
Accelerating microbiome research with OpenACC
Accelerating microbiome research with OpenACCAccelerating microbiome research with OpenACC
Accelerating microbiome research with OpenACC
 
What Shazam doesn't want you to know
What Shazam doesn't want you to knowWhat Shazam doesn't want you to know
What Shazam doesn't want you to know
 

Plus de awwaiid

Plus de awwaiid (8)

2015-10-07 PPDC HTTP Adapters
2015-10-07 PPDC HTTP Adapters2015-10-07 PPDC HTTP Adapters
2015-10-07 PPDC HTTP Adapters
 
2016-05-12 DCRUG React.rb
2016-05-12 DCRUG React.rb2016-05-12 DCRUG React.rb
2016-05-12 DCRUG React.rb
 
Random. Kinda.
Random. Kinda.Random. Kinda.
Random. Kinda.
 
Mad Science: Polyglot Bridges
Mad Science: Polyglot BridgesMad Science: Polyglot Bridges
Mad Science: Polyglot Bridges
 
A Partial Multiverse Model of Time Travel for Debugging
A Partial Multiverse Model of Time Travel for DebuggingA Partial Multiverse Model of Time Travel for Debugging
A Partial Multiverse Model of Time Travel for Debugging
 
Rakudo
RakudoRakudo
Rakudo
 
RailsGirls DC 2012 - Debugging
RailsGirls DC 2012 - DebuggingRailsGirls DC 2012 - Debugging
RailsGirls DC 2012 - Debugging
 
PPW2007 - Continuity Project
PPW2007 - Continuity ProjectPPW2007 - Continuity Project
PPW2007 - Continuity Project
 

Dernier

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Dernier (20)

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

NoiseGen at Arlington Ruby 2012