-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudio_out_tone_code.py
More file actions
49 lines (37 loc) · 1.01 KB
/
audio_out_tone_code.py
File metadata and controls
49 lines (37 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import time
import array
import math
import digitalio
from audiocore import RawSample
# Catch errors from lack of support:
try:
from audioio import AudioOut
except ImportError:
try:
from audiopwmio import PWMAudioOut as AudioOut
except ImportError:
pass
button = digitalio.DigitalInOut(board.A1)
button.switch_to_input(pull=digitalio.Pull.UP)
# Change up/down to adjust volume:
tone_volume = 0.25
# Change the tone frequency to adjust pitch/Hz:
tone_freq = 440
length = 8000 // tone_freq
# Generate sine wave:
sine_wave = array.array("H", [0] * length)
for i in range(length):
sine_wave[i] = int(
1 + math.sin(math.pi * 2 * i / length) * tone_volume * (2 ** 15 - 1)
)
audio = AudioOut(board.A0)
# Create sound sample with the sine wave:
sine_wave_sample = RawSample(sine_wave)
while True:
if not button.value:
# Play the tone:
audio.play(sine_wave_sample, loop=True)
# Wait a bit:
time.sleep(1)
# Stop the tone:
audio.stop()