Mopidy Discourse

Turn speakers on and off programmatically from musicbox webclient

I have PiMusicBox running on a RPi Zero. Sound is output via a USB soundcard to an amplifier module and from there to flushmount speakers. The speakers buzz and crackle when there is nothing playing, especially when theres a cell phone call or the like nearby so I put the amp modual on a wifi relay and can now turn on and off the speakers with relays.local.ip/speakers-on or /speakers-off.

I’d like to have the webclient turn on the speakers just before it starts playing and turn them off after n minutes of no playing.

Turning on seems simpler, just a matter of sticking the GET request into the player, but I have no idea how to implement that.
Turning off after n minutes of no playing I imagine is more complex.

I’m an amature coder and not very proficient in python, js, or html but I can follow intructions.

I’m running a fairly old version of musicbox, running in python2.7

The path to my instalation is /usr/local/lib/python2.7/dist-packages/mopidy_musicbox_webclient

Can anyone help me implement this?

Hmm. I use a Pi Zero with the Pimoroni PhatDAC or IQAudio DAC into a powered speaker and I’ve never had any problems like you mentioned.
I would guess that one of the parts in your setup is causing the problem, and should be replaced. Not sure which though.

Thanks. I’m not looking to replace anything. I already have a way to turn off the speakers when not in use. I’d just like to automate that.

So I’m mostly there. I’m sure there are more elegant ways but here’s what I did, in gui.js.

mopidy.on('event:playbackStateChanged', function (data) {
switch (data.new_state) {
    case 'paused':
    case 'stopped':
        controls.setPlayState(false)
        const speakerOffTimer = setTimeout( () => fetch('http://192.168.0.99/relay=OFF'), 30 * 1000)

        break
    case 'playing':
        fetch('http://192.168.0.99/relay=ON')
        clearTimeout(speakerOffTimer)
        controls.setPlayState(true)
        break
}

})

My problem is that the clearTimeout() doesn’t seem to be working. Speakers turn on when play starts and turn off 30 seconds after it pauses or stops. But if I pause it for less than 30 seconds, they still turn off after 30 seconds from the pause, even the current start is playing.

Is this a scope issue? Does clearTimeout in case:‘playing’ not see speakerOffTimer in case:‘stopped’?

It was a scope issue. Here’s my working version.

let speakerOffTimer;
mopidy.on('event:playbackStateChanged', function (data) {
switch (data.new_state) {
case 'paused':
case 'stopped':
    controls.setPlayState(false)
    speakerOffTimer = setTimeout( () => fetch('http://192.168.0.99/relay=OFF'), 30 * 1000)
    break
case 'playing':
    fetch('http://192.168.0.99/relay=ON')
    clearTimeout(speakerOffTimer)
    controls.setPlayState(true)
    break
}

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.