Skip to content

Commit f658ced

Browse files
committed
Adding PWM audio code
Adding PWM audio example code for the new PWM audio template page
1 parent 789a649 commit f658ced

File tree

3 files changed

+84
-0
lines changed

3 files changed

+84
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# SPDX-FileCopyrightText: 2018 Kattni Rembor for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
"""
6+
CircuitPython PWM Audio Out tone example
7+
Plays a tone for one second on, one
8+
second off, in a loop.
9+
10+
Remove this line and all of the following docstring content before submitting to the Learn repo.
11+
12+
Update the audio out pin to match the wiring chosen for the microcontroller.
13+
Update the following pin name to a viable pin:
14+
* AUDIO_OUTPUT_PIN
15+
"""
16+
import time
17+
import array
18+
import math
19+
import board
20+
from audiocore import RawSample
21+
22+
try:
23+
from audioio import AudioOut
24+
print("Using AudioOut")
25+
except ImportError:
26+
try:
27+
from audiopwmio import PWMAudioOut as AudioOut
28+
print("Using PWMAudioOut")
29+
except ImportError:
30+
pass
31+
32+
audio = AudioOut(board.AUDIO_OUTPUT_PIN)
33+
34+
tone_volume = 0.1 # Increase this to increase the volume of the tone.
35+
frequency = 440 # Set this to the Hz of the tone you want to generate.
36+
length = 8000 // frequency
37+
sine_wave = array.array("H", [0] * length)
38+
for i in range(length):
39+
sine_wave[i] = int((1 + math.sin(math.pi * 2 * i / length)) * tone_volume * (2 ** 15 - 1))
40+
41+
sine_wave_sample = RawSample(sine_wave)
42+
43+
while True:
44+
audio.play(sine_wave_sample, loop=True)
45+
time.sleep(1)
46+
audio.stop()
47+
time.sleep(1)
Binary file not shown.
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# SPDX-FileCopyrightText: 2018 Kattni Rembor for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
"""
6+
CircuitPython PWM Audio Out WAV example
7+
Play a WAV file once.
8+
9+
Remove this line and all of the following docstring content before submitting to the Learn repo.
10+
11+
Update the audio out pin to match the wiring chosen for the microcontroller.
12+
Update the following pin name to a viable pin:
13+
* AUDIO_OUTPUT_PIN
14+
"""
15+
import board
16+
from audiocore import WaveFile
17+
18+
try:
19+
from audioio import AudioOut
20+
print("Using AudioOut")
21+
except ImportError:
22+
try:
23+
from audiopwmio import PWMAudioOut as AudioOut
24+
print("Using PWMAudioOut")
25+
except ImportError:
26+
pass # not always supported by every board!
27+
28+
audio = AudioOut(board.AUDIO_OUTPUT_PIN)
29+
30+
with open("StreetChicken.wav", "rb") as wave_file:
31+
wave = WaveFile(wave_file)
32+
print("Playing wav file!")
33+
audio.play(wave)
34+
while audio.playing:
35+
pass
36+
37+
print("Done!")

0 commit comments

Comments
 (0)