Skip to content

tone: Work with 4.x, 5.0; AudioOut and PWMAudioOut #46

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Sep 16, 2019
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 42 additions & 19 deletions simpleio.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,46 @@
* Author(s): Scott Shawcroft
"""
import time
import sys
try:
import audioio
except ImportError:
pass # not always supported by every board!
import array
import digitalio
import pulseio

#pylint: disable=invalid-name
def _AudioOut(pin):
try:
import audioio
except ImportError:
pass
else:
return audioio.AudioOut(pin)

try:
import audiopwmio
except ImportError:
pass
else:
return audiopwmio.PWMAudioOut(pin)

raise RuntimeError("AudioOut not available")

def _RawSample(buffer):
try:
import audiocore
except ImportError:
pass
else:
return audiocore.RawSample(buffer)

try:
import audioio
except ImportError:
pass
else:
return audioio.RawSample(buffer)

raise RuntimeError("AudioOut not available")
#pylint: enable=invalid-name

def tone(pin, frequency, duration=1, length=100):
"""
Generates a square wave of the specified frequency on a pin
Expand All @@ -61,21 +92,13 @@ def tone(pin, frequency, duration=1, length=100):
square_wave = array.array("H", [0] * sample_length)
for i in range(sample_length / 2):
square_wave[i] = 0xFFFF
if sys.implementation.version[0] >= 3:
square_wave_sample = audioio.RawSample(square_wave)
square_wave_sample.sample_rate = int(len(square_wave) * frequency)
with audioio.AudioOut(pin) as dac:
if not dac.playing:
dac.play(square_wave_sample, loop=True)
time.sleep(duration)
dac.stop()
else:
sample_tone = audioio.AudioOut(pin, square_wave)
sample_tone.frequency = int(len(square_wave) * frequency)
if not sample_tone.playing:
sample_tone.play(loop=True)
square_wave_sample = _RawSample(square_wave)
square_wave_sample.sample_rate = int(len(square_wave) * frequency)
with _AudioOut(pin) as dac:
if not dac.playing:
dac.play(square_wave_sample, loop=True)
time.sleep(duration)
sample_tone.stop()
dac.stop()



Expand Down