Play WAVE files from WSL

I was generating an audio file on WSL and wanted to play it from a command. It was an exaggeration to run the sound server, so I made a simple program in Python on the Windows side and called it via a wrapper.

Library

In the next article, you'll find a lot of Python sound libraries.

This time we will use playsound. Install with pip on Python on the Windows side.

Library installation


py.exe -m pip install playsound

Body

playsound is easy to use by simply importing and passing the filename.

Added a function to specify multiple files and display the name of the file being played. (-P option)

winplay.py


import sys, playsound
if len(sys.argv) < 2:
    print("usage: %s [-p] sound [...]" % sys.argv[0])
    print("    -p: show file name")
    exit(1)
argp = 2 if sys.argv[1] == "-p" else 1
args = sys.argv[argp:]
argl = len(args)
format = "[%%%dd/%%d] %%s" % len(str(argl))
for i, arg in enumerate(args):
    if argp > 1: print(format % (i + 1, argl, arg))
    playsound.playsound(arg)

WSL

Place wintts.py somewhere visible to Windows. Write a simple wrapper like the following and place it wherever the path is in WSL and add the execute attribute.

winplay


#!/bin/sh
py.exe 'C:\Script storage\winplay.py' "$@"

You can now use it as if it were a WSL command.

Example of use


winplay test.wav
winplay -p *.wav

MP3

MP3s can be played for the time being, but in my environment, playback was interrupted and other phenomena occurred.

About the name

I prefixed it with win- to indicate that it works on the Windows side.

Actually, at first, I tried to name the library as it is playsound, but I canceled it because I was addicted to import.

Related Links

Opinions similar to this method are written.

However, if you think about it, you can also run Windows exe from wsl, so if you have an exe that can play wav files, you can use it to make a sound.

As mentioned there, there is a way to get the sound server working.

Recommended Posts

Play WAVE files from WSL
Play audio files from Python with interrupts
Transition from WSL1 to WSL2
Information extraction from EDINET XBRL files
Read and use Python files from Python
Bring files in Windows to WSL
Spark play with WSL anaconda jupyter (2)
Extract strings from files in Python