node-sonos is a free, open source internet of things (iot) project written in JavaScript and released under MIT. It has 723 GitHub stars, 140 forks and 25 open issues, and was last pushed 5 months ago. On this registry it ranks #86 of 99 tracked projects in Internet of Things (IoT), with 5 head-to-head comparisons available.

What is node-sonos?

node-sonos is a JavaScript (Node.js) client library, published on npm as sonos, that lets developers discover Sonos speakers on a local network and control playback, queues, volume, groups and alarms from their own applications.

What it is

node-sonos is an MIT-licensed Node.js library that wraps Sonos device discovery and control behind a JavaScript API. It lives in the npm ecosystem, installs as the sonos package, and exposes two main entry points: DeviceDiscovery (plus the promise-based AsyncDeviceDiscovery) for finding players on the network, and the Sonos(host, [port]) class for controlling a known device. The README states the goal directly: it "gives you the power to control all your Sonos devices from your own apps in JavaScript."

The concrete problem it solves is the absence of a usable JavaScript control layer for Sonos hardware. Without it, an application that wants to pause a speaker, enqueue a track, mute a room or react to a track change would have to build its own device discovery and control code. node-sonos replaces that work with a documented API: it automatically discovers devices, controls playback and the queue, and emits instant events when state changes.

Key capabilities

  • Network device discovery via DeviceDiscovery([options], [deviceAvailableListener]), the 'DeviceAvailable' event, and the asynchronous AsyncDeviceDiscovery class with discover() and discoverMultiple().
  • Playback and queue control through play(uri), pause(), stop(), next(), previous(), togglePlayback(), seek(seconds), queue(uri, positionInQueue), queueNext(uri), getQueue() and flush().
  • Change events announced instantly, including 'CurrentTrack', 'NextTrack', 'PlayState', 'PlaybackStopped', 'AVTransport', 'Volume', 'Muted' and 'RenderingControl', started and stopped with startListening(options) and stopListening().
  • Volume, mute and status-LED control via getVolume(), setVolume(volume), getMuted(), setMuted(muted), getLEDState() and setLEDState(desiredState).
  • Group and topology management with getAllGroups(), joinGroup(otherDeviceName) and leaveGroup(), which the README names as the replacement for getTopology().
  • Spotify and radio support, including setSpotifyRegion(region), plus music library search through getMusicLibrary(search, options) and DIDL parsing with parseDIDL(didl).
  • Alarm clock handling through alarmClockService() with ListAlarms(), SetAlarm(id, enabled) and PatchAlarm(id, options).

Who uses it and how

  • Home-automation bridges: sonos2mqtt bridges Sonos to an MQTT server, and homebridge-zp exposes Sonos ZonePlayers to Homebridge.
  • Apple ecosystem integration: AirSonos adds Apple AirPlay support from iOS and OS X to all Sonos devices on a network.
  • Command-line and chat control: sonos-cli provides a terminal interface, and ZenMusic controls Sonos through Slack.
  • Web and appliance front ends: sonos-web is a browser-based Sonos controller, and gladys-sonos plugs Sonos into Gladys, a Raspberry Pi home assistant.
  • Media and sensor experiments: BudgieStream streams system output to Sonos, and GrooveSensor triggers Sonos on motion.

Getting started

Install the published version with npm install sonos, or track the repository with npm install git://github.com/bencevans/node-sonos.git. Then require it in Node.js, call DeviceDiscovery((device) => {...}) to find players, or construct new Sonos('192.168.1.56') for a known host.

How it compares

The facts name no paid products this library replaces, so the comparison here is with the tools built on top of it: AirSonos, sonos-cli, sonos2mqtt, homebridge-zp, ZenMusic, gladys-sonos, sonos-web, BudgieStream and GrooveSensor. Those are applications and integrations, not competitors; node-sonos is the library underneath several of them, so the choice is usually between adopting the library and adopting one of those finished tools.

When to use it โ€” and when not to

Choose node-sonos when building a Node.js service, bridge or integration that needs programmatic Sonos control, and expect to run that process on the same local network as the speakers, since discovery is network-based. Do not choose it if a finished controller is the goal โ€” the listed apps fill that role โ€” and note that the README is short, with documentation generated from jsdoc comments plus an examples directory rather than a full guide. One known limitation is explicit: getTopology() no longer works on Sonos v9.1 and later, so group handling should use getAllGroups().

project readme (upstream, from github) โ€” read inline


node-sonos logo

node-sonos

Control your Sonos devices with JavaScript (node.js)

GitHub Actions Build NPM Version NPM Downloads Standard Codestyle Discord badge

node-sonos gives you the power to control all your Sonos devices from your own apps in JavaScript. Automatically discover your devices on the network and control the playback and queue with instant events announcing change.

Features

  • Device Discovery
  • Queue Control
  • Volume Control
  • Spotify Support
  • Radio
  • Change Events

Install

Published versions (recommended)

$ npm install sonos

From the repo, living on the edge

$ npm install git://github.com/bencevans/node-sonos.git

Quick Start

Discovering Devices

const { DeviceDiscovery } = require('sonos')

// event on all found...
DeviceDiscovery((device) => {
  console.log('found device at ' + device.host)

  // mute every device...
  device.setMuted(true)
    .then(d => console.log(`${d.host} now muted`))
})

// find one device
DeviceDiscovery().once('DeviceAvailable', (device) => {
  console.log('found device at ' + device.host)

  // get all groups
  device.getAllGroups().then(groups => {
    groups.forEach(group => {
      console.log(group.Name);
    })
  })
})

Discovering devices async

const DeviceDiscovery = require('sonos').AsyncDeviceDiscovery
let discovery = new DeviceDiscovery()
discovery.discover().then((device, model) => {
    // Do stuff, see examples/devicediscovery.js
})

Controlling Known Devices

const { Sonos } = require('sonos')

const device = new Sonos('192.168.1.56');

device.play()
  .then(() => console.log('now playing'))

device.getVolume()
  .then((volume) => console.log(`current volume = ${volume}`))

API

  • DeviceDiscovery([options], [deviceAvailableListener])
  • Class: DeviceDiscovery([options])
    • Event: 'DeviceAvailable'
    • destroy()
  • Class: 'AsyncDeviceDiscovery'
    • discover([options])
    • discoverMultiple([options])
  • Class: Sonos(host, [port])
    • currentTrack()
    • deviceDescription()
    • flush()
    • getCurrentState()
    • getLEDState()
    • getMusicLibrary(search, options)
    • getMuted()
    • getTopology() Doesn't work if you upgraded to Sonos v9.1. Check-out getAllGroups() for some replacement.
    • getVolume()
    • getZoneAttrs()
    • getZoneInfo()
    • getQueue()
    • next()
    • parseDIDL(didl)
    • pause()
    • play(uri)
    • togglePlayback()
    • previous()
    • queue(uri, positionInQueue)
    • queueNext(uri)
    • request(endpoint, action, body, responseTag)
    • seek(seconds)
    • setLEDState(desiredState)
    • setMuted(muted)
    • setName(name)
    • getPlayMode()
    • setPlayMode(mode)
    • setVolume(volume)
    • stop()
    • setSpotifyRegion(region)
    • alarmClockService()
      • ListAlarms()
      • PatchAlarm(id,options)
      • SetAlarm(id,enabled)
    • joinGroup(otherDeviceName)
    • leaveGroup()
    • getAllGroups()
    • startListening(options)
    • stopListening()
    • Event: 'CurrentTrack'
    • Event: 'NextTrack'
    • Event: 'PlayState' and 'PlaybackStopped'
    • Event: 'AVTransport'
    • Event: 'Volume'
    • Event: 'Muted'
    • Event: 'RenderingControl'

Documentation

We tried to add jsdoc info to all functions, and generate documentation from it. /docs

Examples

Additional examples can be found in the /examples directory within the repository.

In The Wild

node-sonos in use across the interwebs. Missing yours? Add it and send us a pull request!

Apps

Writeups

Maintainers

  • Ben Evans (@bencevans)
  • Stephen Wan (@stephen)
  • Marshall T. Rose (@mrose17)
  • Stephan van Rooij (@svrooij)

Contributors โœจ

All Contributors

Thanks goes to these wonderful people (emoji key):

This project follows the all-contributors specification. Contributions of any kind welcome! You can get added by mentioning the @all-contributors bot in a pr or issue.

If we missed you, just go to your (closed) issue or pr and mention the bot to get added.

Issues

If you got discovered an issue with this library, please check the issue-tracker. And create an issue if your problem isn't discovered by someone else. If you want to contribute something check out these 'help-wanted' issues.

Questions

Join us on Discord

The best place to ask your questions is in Discord, we are there to help you. Join us on Discord.

Unsupported sonos features

There is a great other library to control Sonos with Python, they also have a great list of all possible soap actions here. So if you have anything that you cannot do with node-sonos but that you can with the official app. You could have a look in the above list, or use wireshark to investigate the protocol.

NPM publish

We try to react to all pull-requests, but if you think we don't respond in time, please don't create a 'sonos-by-xyz' or a 'node-sonos-by-xyz' package on NPM. This might lead to people installing the wrong version.

If you want to publish your own version, please do it as a user-scoped eg. @svrooij/sonos package.

  1. Change the top of the readme to state your specific changes.
  2. Change the name of the project to @npm_username/sonos
  3. Publish it to npm npm publish --access=public

Development

If you want to make this library better, you can follow these steps.

  1. Create a fork
  2. Make changes
  3. (optional) Create tests for the feature or the bug, see sonos.test.js.
  4. Run SONOS_HOST=192.168.x.x npm run test to test your code (against an actual sonos device, change the ip)
  5. Check-in your code in a single commit. Make sure your commit starts with fix: for a bugfix or feat: for a new feature followed by a short description. You can also follow with an empty line followed by a more details description.
  6. Send a pull-request
  7. Hold-on, we will be checking them.

If you already had a fork, make sure it is updated with the latest master so things don't get complicated when we want to merge the PR.

git remote add upstream https://github.com/bencevans/node-sonos.git
git fetch upstream
git checkout master
git rebase upstream/master
git push origin

Licence

MIT ยฉ Ben Evans

Frequently asked questions

Is node-sonos free to use?

node-sonos is open source under the MIT licence. There is no licence fee and no seat count โ€” you can self-host it or, where the project offers one, pay a vendor for a managed version instead.

What does node-sonos do?

๐Ÿ”ˆ Sonos Media Player Interface/Client

What is node-sonos written in?

node-sonos is primarily written in JavaScript. Its source is publicly available at https://github.com/bencevans/node-sonos, and it has 723 GitHub stars.