Wednesday, June 09, 2021

Coding Your Way to Sleep: Sleep Stories + Tasker

Shira recently discovered Sleep Stories. As the name suggests, this a genre of audio short stories with the goal of putting the listener to sleep. They're heavy on visualization and light on plot and are delivered in a soothing voice designed to lull you to dreamland.

They work great for Shira, not so much for me. The few that we've listened to, I've managed to stay awake the whole time. But as a sort of guided meditation, they work well.

Listening to our first story we hit a snag: Shira had YouTube's auto-play turned on, which meant that once the story finished, an ad started playing. Not cool. For the next story, Shira made sure to disable auto-play, which was an improvement.

What we wanted was a sleep function that a number of apps have: after the selected number of minutes, the audio of the app fades out. YouTube doesn't offer this, but with a bit of hacking I was confident I could get Tasker to do the job.

Between Tasker's 'Media Volume' and 'Wait' actions, it was straightforward task to build. I used Tasker's relatively new Input Dialog action to prompt the user for the number of minutes before the phone's media volume should go to 0.

Looking at the code, you'll notice that the heavy lifting is done in JavaScript. That's because it's faster for me to write JavaScript than tap away at the Tasker UI constructing individual actions. I always need to refresh my memory when working with JavaScriplets as to how variables are handled. As a reference to my future self, here's a few tips:

  • Local variables (like total_sleep) are automatically available
  • To update a local array, you can make calls with the shape: setLocal("arrayName1")
  • To access global variables call global(varname) such as global("VOLM").
  • Many (all?) actions can be called directly from JavaScript. For example: flash("some text") or mediaVol(level, dialog, beep). Clicking the magnifying glass while in the JavaScriplet editor brings up the list of functions you can call.

Download the task here: Tasker Sleep Timer Task.

Sweet dreams!

No comments:

Post a Comment