I did a quick and dirty volume remote control for my Win7 PC and decided to share it.
The script opens a TCP server on the machine, and listens for connections. When a client connects, it will react to commands 'U' (volume up), 'D' (volume down) and 'M' (toggle mute).
It works at least with
Python 3.4 and it uses
NirCmd to set the Windows master volume. I first looked at pywin32 library for the volume control, but I couldn't find any good documentation, so I went the easier route and decided to use NirCmd instead.
It might not be the prettiest solution, but it works for me!
Place the below code into a .py file, for example 'rcserver.py' and run it with Python 3.4. Also place nircmd.exe in the same directory.
You can try it out by using
PuTTy and connecting to 127.0.0.1 port 5005 with 'Raw' connection type. Then enter M, D, U and your computer's volume will change.
I'm using a Raspberry Pi to control it with netcat. Here's how:
Install netcat if you don't have it:
apt-get update
apt-get install netcat
Send mute command:
echo -n "M" | nc -q1 ip.address.of.computer 5005
This echoes a M character to the IP address on port 5005, and quits after one second.
Replace the IP address here and in the Python code with your Windows computer's LAN address.
Note that you can remote control almost anything by adding commands to the script.
Here is the code:
# Python 3 server for Windows 7 remote control
# Juho-Eric 11. Dec 2014
#
# You need the following to run this:
#
# Python 3.4
# https://www.python.org/
#
# NirCmd
# http://www.nirsoft.net/utils/nircmd.html
#
# Place nircmd.exe in the same directory as this script.
import socket
import subprocess
#Parameters for TCP server.
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 20
#This code is to hide the command prompt window when running nircmd.exe
si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
#si.wShowWindow = subprocess.SW_HIDE # default
#Create the TCP server socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
#Main loop, this will loop on each connection
while 1:
conn, addr = s.accept() #get new connection
print('Connection address:', addr)
while 1: #This will loop on each command received
data = conn.recv(BUFFER_SIZE) #receive data
if not data: break #check if connection closed
print("received data:", data)
if data == b'U':
print('volume up')
subprocess.call('nircmd.exe changesysvolume 1000', startupinfo=si) #increase volume
subprocess.call('nircmd.exe mutesysvolume 0', startupinfo=si) #remove mute
elif data == b'D':
print('volume down')
subprocess.call('nircmd.exe changesysvolume -1000', startupinfo=si) #decrease volume
subprocess.call('nircmd.exe mutesysvolume 0', startupinfo=si) #remove mute
elif data == b'M':
print('mute toggle')
subprocess.call('nircmd.exe mutesysvolume 2', startupinfo=si) #toggle mute
conn.close() #close the connection
print("connection closed")