Skip to content

Commit e4ef881

Browse files
authored
Merge pull request #46 from jepler/issue45
tone: Work with 4.x, 5.0; AudioOut and PWMAudioOut
2 parents 5b20cda + 429426b commit e4ef881

File tree

1 file changed

+19
-18
lines changed

1 file changed

+19
-18
lines changed

simpleio.py

+19-18
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,22 @@
2929
"""
3030
import time
3131
import sys
32-
try:
33-
import audioio
34-
except ImportError:
35-
pass # not always supported by every board!
3632
import array
3733
import digitalio
3834
import pulseio
35+
try:
36+
# RawSample was moved in CircuitPython 5.x.
37+
if sys.implementation.version[0] >= 5:
38+
import audiocore
39+
else:
40+
import audioio as audiocore
41+
# Some boards have AudioOut (true DAC), others have PWMAudioOut.
42+
try:
43+
from audioio import AudioOut
44+
except ImportError:
45+
from audiopwmio import PWMAudioOut as AudioOut
46+
except ImportError:
47+
pass # not always supported by every board!
3948

4049
def tone(pin, frequency, duration=1, length=100):
4150
"""
@@ -61,21 +70,13 @@ def tone(pin, frequency, duration=1, length=100):
6170
square_wave = array.array("H", [0] * sample_length)
6271
for i in range(sample_length / 2):
6372
square_wave[i] = 0xFFFF
64-
if sys.implementation.version[0] >= 3:
65-
square_wave_sample = audioio.RawSample(square_wave)
66-
square_wave_sample.sample_rate = int(len(square_wave) * frequency)
67-
with audioio.AudioOut(pin) as dac:
68-
if not dac.playing:
69-
dac.play(square_wave_sample, loop=True)
70-
time.sleep(duration)
71-
dac.stop()
72-
else:
73-
sample_tone = audioio.AudioOut(pin, square_wave)
74-
sample_tone.frequency = int(len(square_wave) * frequency)
75-
if not sample_tone.playing:
76-
sample_tone.play(loop=True)
73+
square_wave_sample = audiocore.RawSample(square_wave)
74+
square_wave_sample.sample_rate = int(len(square_wave) * frequency)
75+
with AudioOut(pin) as dac:
76+
if not dac.playing:
77+
dac.play(square_wave_sample, loop=True)
7778
time.sleep(duration)
78-
sample_tone.stop()
79+
dac.stop()
7980

8081

8182

0 commit comments

Comments
 (0)