Skip to content

Commit f4257fb

Browse files
committed
stk example
1 parent 39c2cb6 commit f4257fb

File tree

2 files changed

+99
-0
lines changed

2 files changed

+99
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#pragma once
2+
#include "StkAllh.h"
3+
4+
/**
5+
* @brief Demo how you can compose your own instrument
6+
* @author Phil Schatzmann
7+
*/
8+
class MyFirstInstrument : public Instrmnt {
9+
public:
10+
MyFirstInstrument() {
11+
adsr.setAllTimes( 0.005, 0.01, 0.8, 0.010 );
12+
echo.setDelay(1024);
13+
}
14+
15+
//! Start a note with the given frequency and amplitude.
16+
void noteOn( StkFloat frequency, StkFloat amplitude ) {
17+
wave.setFrequency(frequency);
18+
adsr.keyOn();
19+
}
20+
21+
//! Stop a note with the given amplitude (speed of decay).
22+
void noteOff( StkFloat amplitude ){
23+
adsr.keyOff();
24+
}
25+
26+
float tick() {
27+
return echo.tick(wave.tick())*adsr.tick();
28+
}
29+
30+
protected:
31+
stk::SineWave wave;
32+
stk::ADSR adsr;
33+
stk::Echo echo {1024};
34+
};
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/**
2+
* @file streams-stk-audioout.ino
3+
* @brief Plays random notes on self designed instrument: see https://github.com/pschatzmann/Arduino-STK/wiki/Building-your-own-Instrument
4+
* @author Phil Schatzmann
5+
* @copyright Copyright (c) 2021
6+
*/
7+
#include "AudioTools.h"
8+
#include "AudioLibs/AudioSTK.h"
9+
#include "AudioLibs/AudioKit.h"
10+
#include "MyFirstInstrument.h"
11+
12+
MyFirstInstrument instrument;
13+
STKStream<Instrmnt> in(instrument);
14+
AudioKitStream out;
15+
StreamCopy copier(out, in);
16+
MusicalNotes notes;
17+
18+
float note_amplitude = 0.5;
19+
static uint16_t notes_array[] = { // frequencies aleatoric C-scale
20+
N_C3, N_D3, N_E3, N_F3, N_G3, N_A3, N_B3,
21+
N_C4, N_D4, N_E4, N_F4, N_G4, N_A4, N_B4,
22+
N_C5, N_D5, N_E5, N_F5, N_G5, N_A5, N_B5
23+
};
24+
25+
void play() {
26+
static bool active=true;
27+
static float freq;
28+
static uint64_t timeout;
29+
30+
if (millis()>timeout){
31+
if (active){
32+
// play note for 800 ms
33+
freq = notes_array[random(sizeof(notes_array)/sizeof(uint16_t))];
34+
instrument.noteOn(freq, note_amplitude);
35+
timeout = millis()+800;
36+
active = false;
37+
} else {
38+
// silence for 100 ms
39+
instrument.noteOff(note_amplitude);
40+
timeout = millis()+100;
41+
active = true;
42+
}
43+
}
44+
}
45+
46+
void setup() {
47+
Serial.begin(115200);
48+
AudioLogger::instance().begin(Serial,AudioLogger::Warning);
49+
50+
// setup input
51+
auto icfg = in.defaultConfig();
52+
in.begin(icfg);
53+
54+
// setup output
55+
auto ocfg = out.defaultConfig(TX_MODE);
56+
ocfg.copyFrom(icfg);
57+
ocfg.sd_active = false;
58+
out.begin(ocfg);
59+
60+
}
61+
62+
void loop() {
63+
play();
64+
copier.copy();
65+
}

0 commit comments

Comments
 (0)