Skip to content

Samples

Build and run the sense-file and sense-stream samples in Python, C++, or Android, with the config and result formats they use.

Two samples are provided with Cochl.Sense Core: sense-file and sense-stream.

  • sense-file runs inference on an audio file (WAV or MP3).
  • sense-stream runs inference on a live audio buffer (e.g. a microphone).

Make sure your environment is set up first — see Getting started. Every platform below shares the same three preparation steps — clone the tutorial, download the SDK, unzip the SDK into the tutorial — and needs these command-line tools. On Linux hosts:

sudo apt update
sudo apt install -y git unzip curl

Then pick the platform you're targeting. Each tab follows the same order: Requirements → Prepare → License manager → Usage → Build & run → Reference → Removed in v1.6.1 → Troubleshooting. Android has no License manager step (the license runs in-process) and no Troubleshooting section.

1. Python requirements

Cochl.Sense Core for Python supports Python 3.6–3.12. The wheel is a compiled, version-specific build, so you must download the file that matches both your Python version and CPU architecture (e.g. cp38 for Python 3.8, aarch64 for a 64-bit Raspberry Pi). If you need a version that is not listed, contact support@cochl.ai.

In addition to the shared git unzip curl tools above, install the Python build tools and the PortAudio library the sense-stream sample uses for microphone capture:

sudo apt install -y python3-venv python3-pip libportaudio2

Check your interpreter version first — you'll download the matching SDK in step 2:

python3 --version   # e.g. Python 3.8.10  -> download the cp38 wheel

2. Prepare the sample

(1) Clone the tutorial

git clone https://github.com/cochlearai/sense-sdk-python-tutorials.git

(2) Create and activate a virtual environment

Create the environment with the interpreter whose version matches the SDK you're about to download:

cd sense-sdk-python-tutorials
python3 -m venv ./venv
source ./venv/bin/activate     # prompt is now prefixed with (venv)
python -m pip install --upgrade pip
  • NOTE: For older Python versions (e.g. 3.6, 3.7) the venv module ships in a version-specific package (python3.6-venv, python3.7-venv). Install the one matching your interpreter.

(3) Download the version-matched SDK

Download the wheel package built for your Python version and architecture. Replace cp38 and linux_aarch64 with the values matching your environment — note Python 3.6 and 3.7 use the ABI tags cp36-cp36m / cp37-cp37m, not cp36-cp36 / cp37-cp37. Resources lists the exact link for every version:

# (venv)
curl -LO https://github.com/cochlearai/sense-sdk-python-tutorials/releases/download/v1.6.1/sense-1.6.1-cp38-cp38-linux_aarch64.zip

(4) Unzip the SDK into the tutorial directory

unzip sense-1.6.1-cp38-cp38-linux_aarch64.zip -d .

After unzipping, your sample directory should look like this:

sense-sdk-python-tutorials
    |-- README.md
    |-- config.json          # configuration file used to initialize the SDK
    |-- audio-files          # audio samples
    |-- sense-file           # sense-file sample (sense_file.py)
    |-- sense-stream         # sense-stream sample (sense_stream.py)
    `-- sense                # Cochl.Sense Core library
        |-- sense-1.6.1-cp38-cp38-linux_aarch64.whl
        `-- sl               # license daemon (scripts + binary)

(5) Install the SDK and dependencies

Install the wheel you unzipped. The Sense wheel has no runtime dependencies; the sense-stream sample additionally needs sounddevice (from its requirements.txt):

# (venv)
pip install sense/sense-1.6.1-cp38-cp38-linux_aarch64.whl
pip install -r sense-stream/requirements.txt   # sense-stream only (sounddevice)

3. Install the license manager

The license manager is required as of SDK v1.4.0. As of v1.6.1, it is the native sense-lm backend, which replaced Thales. On Linux it runs as a small system daemon that verifies the license and needs an internet connection. Install it once:

sudo ./sense/sl/scripts/install_daemon.sh

The installer creates a system group sense-lm and adds your user to it. Apply the new group membership without logging out:

newgrp sense-lm     # or log out and back in

To remove the daemon later:

sudo ./sense/sl/scripts/uninstall_daemon.sh

4. How to use Cochl.Sense Core for Python

(1) Initialization

Initialize the SDK with your project key and the contents of config.json. sense.session(...) is a context manager that calls init() on entry and terminate() on exit. Initialization may take some time if a model must be downloaded (the SDK downloads a model when none is present or a newer one is available).

import sense

project_key = "Your project key"  # Replace with your own key
with open("config.json", encoding="utf-8") as f:
    config = f.read()

with sense.session(project_key, config):
    # ... create a processor and run inference here ...
    pass

(2) Configuration

This file stores the SDK's configuration settings. Passing its contents (C++/Python) or its path (Android) to the initialization method lets the SDK read and apply the settings. Every field is optional; omitted fields fall back to the defaults below. A file that isn’t valid JSON doesn’t make initialization fail: the SDK logs a warning (config parse error … using default configuration) and runs with all defaults, so check the log if your settings seem to be ignored.

{
  "device_name": "SenseDevice",
  "num_threads": 0,
  "log_level": "info",
  "app_data_path": "~",
  "default_hopsize": 1.0,
  "metrics": {
    "retention_period": 0,
    "free_disk_space": 100,
    "push_period": 30
  },
  "sensitivity_control": {
    "default_sensitivity": "NORMAL",
    "tag_sensitivity": {
    }
  },
  "result_summary": {
    "enable": false,
    "default_interval_margin": 0,
    "tag_interval_margin": {
    }
  },
  "audio_preprocessor": {
    "audio_activity_detection": {
      "enable": false,
      "history_count": 600,
      "sensitivity": "NORMAL"
    },
    "automatic_gain_control": {
      "enable": false
    }
  }
}
Top-level fields
FieldDefaultDescription
device_name"SenseDevice"Name shown for this device on the Dashboard. Set a distinct device_name on each device. Rename it later on the Devices page of the Dashboard, under Cochl.Sense Core.
num_threads0Threads used for inference. A positive value is the exact count; 0 uses all cores; a negative value counts down from all cores — -1 = all cores, -2 = all cores minus one, -3 = all cores minus two, and so on (result clamped to at least 1).
log_level"info"Log verbosity, as a string: "error", "warn", "info", "debug".
app_data_path"~"Where the SDK stores resources generated during execution (downloaded models, the metrics buffer, server session data), in a .sense-sdk folder under this path. "~" expands to the user's home directory. On Linux the license state is kept by the license daemon in /var/lib/sense-lm/, not here. On Android this is set automatically to the app's private storage — you don't need to configure it.
default_hopsize1.0Inference hop in seconds — how often a result is produced. Clamped to [0.1, 1.0], then rounded to the nearest 0.1.
metricsobjectLocal metrics buffer + push behavior. See below.
sensitivity_controlobjectDetection sensitivity, globally and per tag. See below and Advanced configurations.
result_summaryobjectMerge consecutive same-tag windows into single interval events. See below and Advanced configurations.
audio_preprocessorobjectAudio Activity Detection + Automatic Gain Control (stream mode only). See below and Advanced configurations.
metrics sub-fields

Each inference window produces a metric, buffered locally and pushed to the Dashboard on a schedule.

FieldDefaultUnitDescription
retention_period0daysHow long the SDK keeps unsent metrics locally. 0 disables local saving. Capped at 31 days.
free_disk_space100MBWhen free disk drops below this threshold, the SDK stops storing metrics locally (effectively retention_period: 0). A negative value is treated as 0; a value above 1,000,000 is invalid and falls back to the default 100.
push_period30secondsHow often metrics are pushed to the Dashboard. Capped at 3,600 s.
sensitivity_control sub-fields

Sensitivity levels are strings: "VERY_LOW", "LOW", "NORMAL", "HIGH", "VERY_HIGH".

FieldDefaultDescription
default_sensitivity"NORMAL"Detection sensitivity applied to every tag.
tag_sensitivity{}Per-tag overrides, e.g. { "Glass_break": "VERY_HIGH", "Rustle": "LOW" }. Tags not listed use default_sensitivity.
result_summary sub-fields

When enabled, consecutive windows of the same tag are merged into one interval event (summaries in the result).

FieldDefaultUnitDescription
enablefalse—Turns Result Summary on.
default_interval_margin0secondsGap tolerance for merging same-tag windows into one interval. Whole seconds; a fractional value is cut to an integer.
tag_interval_margin{}secondsPer-tag margin overrides, e.g. { "Speech": 2 }. Values must be integers; other entries are ignored.
audio_preprocessor sub-fields

Both preprocessors apply to stream mode only.

FieldDefaultDescription
audio_activity_detection.enablefalseSkips inference on windows with no audio activity.
audio_activity_detection.history_count600Detection window length, in seconds (a fixed span, independent of hop size).
audio_activity_detection.sensitivity"NORMAL"Activity-detection sensitivity: "VERY_LOW" … "VERY_HIGH".
automatic_gain_control.enablefalseBoosts quiet input (up to 8×, about +18 dB) before inference; never attenuates loud input.

(3) Audio input and prediction

The SDK receives audio and returns detected sound tags. In file mode you point it at a file; in stream mode you push captured audio buffers. Results are delivered to a sense.ResultListener callback (on_result), one call per inference window.

Sample rate. The input must be at or above the model's rate (typically 22,050 Hz). Lower rates are not supported — file mode rejects a below-rate file with a resampling error and stream mode rejects the pushed chunk; higher rates are automatically downsampled. Use processor.model_sample_rate() to capture at the model's native rate.

Create a file processor and start it. start() blocks until the whole file is processed.

Note: a file shorter than the model's window is still processed — the SDK zero-pads the final window; only an empty file is rejected.

import sense

class Printer(sense.ResultListener):
    def on_result(self, frame: sense.Result) -> None:
        if not frame.is_ok():
            print("error:", frame.error)
            return
        for tag in frame.tags:
            print(frame.start_time, tag.name, tag.probability)

listener = Printer()
processor = sense.create_file_processor("audio_file.wav", listener)
processor.start()   # blocks until end of file

(4) Result format

Each inference window produces one result. In stream mode, pushing audio only appends it to an internal FIFO; it does not produce a result for each call. When the buffer contains a full model window, the SDK runs inference, drops the oldest hop, and repeats as long as a full window remains. Pushing less than one window produces no results, while pushing several windows' worth produces several results. Leftover audio stays buffered for the next push; when you stop the stream with processor.stop(), the SDK zero-pads whatever is still buffered to one full window and emits one final result for it. In file mode, the SDK produces one result per window across the entire file.

Your ResultListener.on_result is called once per window with a sense.Result:

class Tag:
    name: str                  # Detected tag, e.g. "Siren"
    probability: float         # Confidence for that tag, 0.0-1.0

class Result:
    tags: List[Tag]            # Empty when nothing passed threshold
    start_time: float          # Window start, seconds
    end_time: float            # Window end, seconds
    prediction_time_ms: float  # Processing time for this window, ms
    timestamp: int             # Unix time (seconds) the window was processed
    summaries: List[str]       # Result Summary lines; empty unless enabled
    error: str                 # Empty on success, message on failure

    def is_ok(self) -> bool: ...   # True when error is empty
FieldTypeNotes
tagsList[Tag]Detected tags; empty for silence or sub-threshold audio — a valid, successful result.
start_timefloatSeconds from the start of the stream or file.
end_timefloatstart_time plus the window length.
prediction_time_msfloatInference latency for this window.
timestampintUnix time, in seconds, when the window was processed.
summariesList[str]Interval lines; only with Result Summary on. Stream mode emits "Listening..." for a window with no interval.
errorstrEmpty on success; non-empty only on failure, with tags then empty.

Check result.is_ok() rather than testing tags — an empty tags means silence, not an error.

(5) Terminate

The SDK allocates resources during initialization. Release them with terminate(). When you use sense.session(...), this happens automatically on exit; call it explicitly only if you used sense.init(...) directly.

import sense

sense.terminate()

5. How to run

Run from the tutorial root so the samples find config.json in the working directory. Set your project key in PROJECT_KEY at the top of sense-file/sense_file.py and sense-stream/sense_stream.py first.

# (venv)
python sense-file/sense_file.py <PATH_TO_AUDIO_FILE>
python sense-file/sense_file.py audio-files/babycry.wav

6. Reference

Import from the sense package.

Module functions

sense.init()
sense.init(project_key, config_json)

Authenticates with the project key and applies the configuration.

ParameterTypeDescription
project_keystrYour project key.
config_jsonstrThe contents of config.json (not a path).

Returns bool. Raises RuntimeError on failure — it does not return False, so if not sense.init(...) never fires. Wrap calls in try / except RuntimeError, or use with sense.session(...), which does it for you.

sense.terminate()
sense.terminate()

Releases all resources allocated during initialization. Returns bool — True on success.

sense.is_initialized()
sense.is_initialized()

Returns bool — whether the SDK is initialized.

sense.session()
sense.session(project_key, config_json)

Context manager that calls init() on entry and terminate() on exit: with sense.session(key, config): .... Parameters are the same as init. Returns a context manager.

sense.create_file_processor()
sense.create_file_processor(file_path, listener)

Creates a file-mode processor.

ParameterTypeDescription
file_pathstrPath to the audio file (WAV or MP3).
listenerResultListenerReceives one on_result call per window.

Returns Processor. Raises RuntimeError on failure.

sense.create_stream_processor()
sense.create_stream_processor(listener)

Creates a stream-mode processor fed by push.

ParameterTypeDescription
listenerResultListenerReceives one on_result call per window.

Returns Processor. Raises RuntimeError on failure.

Processor

Processor.start()
Processor.start()

File mode runs to completion (blocks); stream mode arms the stream. Returns bool. Raises RuntimeError on failure.

Processor.push()
Processor.push(pcm, num_channels, sample_format, input_sample_rate)

Feeds one chunk of captured audio (stream mode); the SDK buffers it internally and runs inference only once a full model window has accumulated — so a single push may deliver zero, one, or several results.

ParameterTypeDescription
pcmbytesInterleaved PCM for one hop.
num_channelsintChannel count (≥ 1).
sample_formatintA SampleFormat value.
input_sample_rateintCapture rate in Hz; must be ≥ model_sample_rate().

Returns bool — True if the chunk was accepted.

Processor.stop()
Processor.stop()

Stops processing. In stream mode, audio still buffered is first zero-padded to one window and delivered as a final result; with Result Summary on, one more result can follow with the closing summaries. Returns bool.

Processor.model_sample_rate()
Processor.model_sample_rate()

Returns int — the model's native sample rate in Hz.

Runtime controls

Runtime feature controls on the processor. AAD/AGC apply to stream mode only. Sensitivity levels are "VERY_LOW" | "LOW" | "NORMAL" | "HIGH" | "VERY_HIGH".

Setter / GetterTypeDescription
set_sensitivity(level) / get_sensitivity()strGlobal detection sensitivity.
set_tag_sensitivity(tag, level) / get_tag_sensitivity(tag)strPer-tag sensitivity.
set_result_summary_enabled(enable) / is_result_summary_enabled()boolMerge same-tag windows into intervals.
set_result_summary_margin(seconds) / get_result_summary_margin()intInterval merge margin (seconds).
enable_audio_activity_detection(enable) / is_audio_activity_detection_enabled()boolSkip inference on inactive audio.
set_aad_sensitivity(level) / get_aad_sensitivity()strActivity-detection sensitivity.
set_aad_history_count(seconds) / get_aad_history_count()intActivity window length (seconds).
enable_automatic_gain_control(enable) / is_automatic_gain_control_enabled()boolBoost quiet input (up to 8×).

ResultListener

Subclass and override on_result(self, frame: Result) -> None. It fires once per inference window on the SDK's inference thread, so keep the callback cheap.

Result

Passed to on_result. is_ok() -> bool reports whether the window succeeded.

FieldTypeDescription
tagsList[Tag]Detected tags; each Tag has name: str, probability: float.
start_time / end_timefloatWindow bounds, in seconds.
prediction_time_msfloatProcessing time, in milliseconds.
timestampintWindow timestamp.
summariesList[str]Interval lines (present when Result Summary is enabled).
errorstrError message (empty when is_ok()).

SampleFormat

SampleFormat.FLOAT32 | INT16 | INT32 | FLOAT64 — the encoding passed to push.

7. Removed in v1.6.1

The pre-1.6 procedural API was replaced by the processor/listener API above. Migrate as follows:

RemovedUse instead
SenseInit(project_key, config_path)sense.init(project_key, config_contents) or sense.session(...)
SenseTerminate()sense.terminate()
AudioSourceFile().Load() + .Predict()sense.create_file_processor(path, listener) + processor.start()
AudioSourceStream().Predict(buffer, rate)sense.create_stream_processor(listener) + processor.push(...)

8. Troubleshooting

If you hit an error, reset the SDK's local state and run again:

rm -rf ~/.sense-sdk

This deletes the downloaded models, the metrics buffer and the server session data; the SDK downloads the model again on the next Init. It does not touch the license, which the daemon keeps in /var/lib/sense-lm/. If you set a custom app_data_path, delete <app_data_path>/.sense-sdk instead. sudo is only needed if you once ran the SDK as root.

Last updated

Need help? Contact support@cochl.ai

For Cochl.Sense Core, include the SDK version and the platform (Python, C++, or Android).

Powered by Cochl