Skip to content

Instantly share code, notes, and snippets.

@nbogie

nbogie/playsound.py

Last active Apr 28, 2018
Embed
What would you like to do?
neill's microbit play raw audio file - first draft
from microbit import display, sleep, button_a
import audio
def frames_from_file(sndfile, frame):
while(sndfile.readinto(frame, 32) > 0):
yield frame
def play_snd(fname):
frame = audio.AudioFrame()
with open(fname, 'rb') as sndfile:
audio.play(frames_from_file(sndfile, frame),wait=False)
sleep(1000)
audio.stop()
del frame
display.show('r')
while True:
if button_a.is_pressed():
play_snd('clip.raw')
sleep(200)
@nbogie

This comment has been minimized.

Copy link
Owner Author

@nbogie nbogie commented Apr 25, 2018

@nbogie

This comment has been minimized.

Copy link
Owner Author

@nbogie nbogie commented Apr 25, 2018

From a suggested plan by David Whale https://twitter.com/gowolade/status/988412562814525440 with one change - this code seems to work much better with unsigned rather than signed bytes for the headerless 8-bit PCM sound files. (There's a huge amount of distortion with the originally suggested format (with my code, which is likely in error).)

This uses the audio example in the microbit micropython docs (by ntoll or markshannon, perhaps): https://github.com/bbcmicrobit/micropython/blob/master/examples/waveforms.py

@nbogie

This comment has been minimized.

Copy link
Owner Author

@nbogie nbogie commented Apr 25, 2018

Issues:

  • there's some clicking at start and stop of sound playback (despite zeros in sample). to investigate.
  • this version waits a fixed time for the sound to finish, it doesn't figure it out from the file size and the (fixed) sample playback rate.
  • not code related: "ufs put" command won't let me put more than about 7kb without failing with err 28, which seems to be out of space.
@nbogie

This comment has been minimized.

Copy link
Owner Author

@nbogie nbogie commented Apr 25, 2018

Here's another one that triggers on receiving a radio message https://gist.github.com/nbogie/0731380a4b5be26cbed45133d59b38cc
I've also improved it to wait the correct amount of time before closing the audio.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment