Audio
Since API 6.0.3
The Toybox.Audio module allows an app to play audio and capture audio on supported devices. Audio playback and capture are available while the app is in the foreground. These APIs are not available to watch faces, data fields, or widgets.
Playback requires the AudioOutput permission, and capture requires the AudioInput permission. An app that uses both features must request both permissions in its manifest. For more information, see Manifest and Permissions.
Audio formats are described by an Audio.AudioFormat dictionary. The same format fields are used when configuring capture or supplying a format for dynamic and streaming sources:
| Option | Description |
|---|---|
:containerFormat | The container format from Audio.ContainerFormat |
:codec | The encoding from Audio.Codec |
:frequency | A sampling frequency from Audio.SamplingFrequency |
:channels | The channel mode from Audio.ChannelMode |
The available formats depend on the device. Before configuring capture, use Capture.isFormatSupported() to check the requested format.
Sources
Audio playback accepts three types of sources: a resource source is bundled with the app, a dynamic source is built from audio data at runtime, and a streaming source supplies data as it is needed during playback. Each source can be passed to Output.play().
Resource
An Audio.AudioResource represents audio that is bundled with an app. For more information on how to create an audio resource, see the Resources section.
Load the resource with Application.loadResource() by passing its identifier from Rez.Audios. The resulting audio resource can be played directly:
import Toybox.Application;
import Toybox.Audio;
import Toybox.Audio.Output;
function playResource() as Void {
var source = Application.loadResource(Rez.Audios.success) as AudioResource;
Output.play(source, 0);
}AudioResource.getFormat() returns the resource's audio format, and AudioResource.getId() returns its resource identifier.
Dynamic
An Output.DynamicAudioSource is built from audio data at runtime. Unlike a streaming source, a dynamic source is completed before it is passed to the output module.
Use an Output.DynamicAudioSourceBuilder to assemble a source from one or more byte arrays. Set the audio format when creating the builder, append the encoded data in order, and call DynamicAudioSourceBuilder.complete() to obtain the playable source. If the format is null, it must be detectable in the first buffer.
The following example takes buffers that together contain a complete audio source in the supplied format:
import Toybox.Audio;
import Toybox.Audio.Output;
import Toybox.Lang;
function playDynamic(buffers as Array<ByteArray>, format as AudioFormat) as Void {
var builder = new Output.DynamicAudioSourceBuilder({:format => format});
for (var i = 0; i < buffers.size(); i += 1) {
builder.append(buffers[i]);
}
var source = builder.complete();
Output.play(source, 0);
}For a complete source held in a single byte array, append the array once and call DynamicAudioSourceBuilder.complete(). The following function accepts a complete WAV container and its audio format dictionary:
import Toybox.Audio;
import Toybox.Audio.Output;
import Toybox.Lang;
function playWav(data as ByteArray, format as AudioFormat) as Void {
var builder = new Output.DynamicAudioSourceBuilder({:format => format});
builder.append(data);
var source = builder.complete();
Output.play(source, 0);
}Streaming
A streaming source allows an app to provide encoded audio data while playback is in progress. Extend Output.StreamingAudioSource and override StreamingAudioSource.onReadyForData() to supply data when the internal buffer gets low, or when the source is played with an empty buffer.
The freeSpace parameter to onReadyForData() is the number of bytes available in the buffer. Call StreamingAudioSource.append() to add data. This method returns the number of bytes that were appended, so keep any bytes that were not accepted for a later call. StreamingAudioSource.getBufferSize() returns the buffer's total capacity in bytes.
Once all data has been supplied, call StreamingAudioSource.end() to indicate that no more data will be added. Override StreamingAudioSource.onError() to handle errors that occur while the source is playing.
The following example feeds a provided byte array through the streaming buffer. The array must contain valid encoded audio in the supplied format. An app that receives data in chunks can use the same pattern to track its pending data.
import Toybox.Audio;
import Toybox.Audio.Output;
import Toybox.Lang;
import Toybox.System;
class BufferedAudioSource extends Output.StreamingAudioSource {
private var _data as ByteArray;
private var _offset as Number;
private var _ended as Boolean;
function initialize(data as ByteArray, format as AudioFormat) {
_data = data;
_offset = 0;
_ended = false;
Output.StreamingAudioSource.initialize({
:format => format,
:bufferSize => 4096
});
}
function onReadyForData(freeSpace as Number) as Void {
if (_ended) {
return;
}
var count = _data.size() - _offset;
if (count > freeSpace) {
count = freeSpace;
}
if (count > 0) {
var buffer = _data.slice(_offset, _offset + count);
_offset += append(buffer);
}
if (_offset == _data.size()) {
_ended = true;
end();
}
}
function onError(error as Output.Error) as Void {
System.println("Audio playback error: " + error);
}
}
function playStream(data as ByteArray, format as AudioFormat) as Void {
var source = new BufferedAudioSource(data, format);
Output.play(source, 0);
}Output
The Audio.Output module controls audio playback. Call Output.play() with a resource, dynamic, or streaming source and a startPosition argument. This argument specifies the starting playback position in milliseconds. Pass 0 to play from the beginning.
The playback controls allow you to pause, resume, stop, or restart the last played source:
| Function | Purpose | API Version |
|---|---|---|
| Output.play() | Play an audio source from the specified starting position | 6.0.3 |
| Output.start() | Play the last played source, resetting the position to zero | 6.0.3 |
| Output.stop() | Stop playback and reset the position to zero | 6.0.3 |
| Output.pause() | Pause playback without resetting the position | 6.0.3 |
| Output.resume() | Play the last played source without resetting the position | 6.0.3 |
| Output.getPosition() | Get the playback position in milliseconds | 6.0.3 |
| Output.seekPosition() | Set the playback position in milliseconds | 6.0.3 |
Output.getState() returns the current playback state from Output.PlaybackState.
Register a method with Output.registerStateChangeHandler() to receive state changes. To track playback progress, use Output.registerPeriodicUpdateHandler() with a period in milliseconds. Its callback receives the current playback position and is called only while a source is playing, not while playback is paused or stopped. Pass null as the callback to either registration method to clear its handler.
If playback fails, Output.getError() returns an Output.Error value. It returns null when there is no error. The error state is cleared when a new source is played.
The following example registers playback handlers and provides a method to stop playback and clear them when the app is finished:
import Toybox.Audio;
import Toybox.Audio.Output;
import Toybox.Lang;
import Toybox.System;
class AudioPlayer {
function initialize() {
}
function play(source as Output.AudioSource) as Void {
Output.registerStateChangeHandler(method(:onStateChange));
Output.registerPeriodicUpdateHandler(1000, method(:onPosition));
Output.play(source, 0);
}
function onStateChange(state as Output.PlaybackState) as Void {
if (state == Output.PLAYBACK_ERROR) {
System.println("Audio playback error: " + Output.getError());
}
}
function onPosition(position as Number) as Void {
System.println("Playback position: " + position + " ms");
}
function close() as Void {
Output.stop();
Output.registerStateChangeHandler(null);
Output.registerPeriodicUpdateHandler(1000, null);
}
}Set the playback volume with Output.setVolume(). The volume is a percentage from 0 to 100. Values outside that range cause a Lang.ValueOutOfBoundsException. Output.incrementVolume() adds the supplied percentage points without increasing the volume above 100, and Output.decrementVolume() subtracts percentage points without decreasing the volume below zero.
Capture
The Audio.Capture module captures audio and delivers encoded data to an app through callbacks. Before initializing capture, use Capture.isFormatSupported() to check the requested format and Capture.getSupportedFilters() to get the filters available on the device. The Audio.Capture.FILTER_NREC filter provides noise reduction and echo cancellation when supported.
Note: Noise reduction and echo cancellation filters are not supported by the simulator and are ignored when requested.
Call Capture.initializeAudioCapture() with a callback object and a settings dictionary. The method returns the settings that will be used for capture, including defaults for options that were not provided:
| Option | Description |
|---|---|
:format | The audio format dictionary describing the container, codec, sampling frequency, and channel mode |
:windowSize | The capture window size in bytes |
:windowFilledBehavior | Whether to stop or continue when the window is filled. The default is `Audio.Capture.WINDOW_FILLED_STOP`. |
:filters | An array of capture filters supported by the device |
With `Audio.Capture.WINDOW_FILLED_STOP`, capture stops when the window is filled. With `Audio.Capture.WINDOW_FILLED_CONTINUE`, capture continues as data is delivered to the app.
The callback object must provide the following methods:
| Callback | Purpose |
|---|---|
onData(audioData) | Receive a Lang.ByteArray of encoded audio data up to the window size |
onError(error) | Receive a Capture.Error code if an error occurs during capture |
onComplete() | Receive notification that capture ended without an error |
After initialization, call Capture.start() to begin capturing. Call Capture.stop() to stop. Stopping capture sends any remaining data to the registered callback, so the app should continue handling data until capture has finished.
The following example checks a format, initializes capture, and prints information about the data received. In an app, onData() can process or retain the encoded data instead:
import Toybox.Audio;
import Toybox.Audio.Capture;
import Toybox.Lang;
import Toybox.System;
class AudioRecorder {
function initialize() {
}
function start() as Void {
var format = {
:containerFormat => Audio.CONTAINER_WAV,
:codec => Audio.CODEC_LPCM,
:frequency => Audio.FREQ_16_KHZ,
:channels => Audio.CHANNEL_MONO
};
if (!Capture.isFormatSupported(format)) {
System.println("Audio capture format is not supported");
return;
}
try {
var settings = Capture.initializeAudioCapture(self, {
:format => format,
:windowSize => 4096,
:windowFilledBehavior => Capture.WINDOW_FILLED_CONTINUE,
:filters => []
});
System.println("Capture window: " + settings[:windowSize] + " bytes");
Capture.start();
} catch (e instanceof Capture.InitializationFailedException) {
System.println("Audio capture initialization error: " + e.getError());
} catch (e instanceof Exception) {
System.println("Audio capture error: " + e.getErrorMessage());
}
}
function stop() as Void {
if (Capture.getState() == Capture.CAPTURE_CAPTURING) {
Capture.stop();
}
}
function onData(audioData as ByteArray) as Void {
System.println("Captured " + audioData.size() + " bytes");
}
function onError(error as Capture.Error) as Void {
System.println("Audio capture error: " + error);
}
function onComplete() as Void {
System.println("Audio capture complete");
}
}Capture.getState() returns Audio.Capture.CAPTURE_UNINITIALIZED when capture is not initialized, Audio.Capture.CAPTURE_STOPPED when it is stopped, or Audio.Capture.CAPTURE_CAPTURING when capture is in progress.