Skip to content

Commit 6b04b76

Browse files
authored
Merge pull request #2464 from adafruit/pwm_audio_template
Adding PWM audio code
2 parents 789a649 + a702405 commit 6b04b76

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
from audiopwmio import PWMAudioOut as AudioOut
22+
23+
audio = AudioOut(board.AUDIO_OUTPUT_PIN)
24+
25+
tone_volume = 0.1 # Increase this to increase the volume of the tone.
26+
frequency = 440 # Set this to the Hz of the tone you want to generate.
27+
length = 8000 // frequency
28+
sine_wave = array.array("H", [0] * length)
29+
for i in range(length):
30+
sine_wave[i] = int((1 + math.sin(math.pi * 2 * i / length)) * tone_volume * (2 ** 15 - 1))
31+
32+
sine_wave_sample = RawSample(sine_wave)
33+
34+
while True:
35+
audio.play(sine_wave_sample, loop=True)
36+
time.sleep(1)
37+
audio.stop()
38+
time.sleep(1)
Binary file not shown.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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+
from audiopwmio import PWMAudioOut as AudioOut
18+
19+
audio = AudioOut(board.AUDIO_OUTPUT_PIN)
20+
21+
with open("StreetChicken.wav", "rb") as wave_file:
22+
wave = WaveFile(wave_file)
23+
print("Playing wav file!")
24+
audio.play(wave)
25+
while audio.playing:
26+
pass
27+
28+
print("Done!")

0 commit comments

Comments
 (0)