Sometimes you want your application to make a sound, for example when a long solve has finished.
This article shows how to play a .wav file from AIMMS with the Python-Bridge and the winsound
module from the Python standard library.
Important
The sound plays on the computer where AIMMS runs. This works when you, or your end user, run the application in AIMMS Developer or as a desktop application on Windows. When the application runs on AIMMS Cloud or AIMMS PRO, AIMMS runs on a server, and the end user hears nothing.
WebUI has no supported way to play a sound in the end user’s browser. The Python code in this article cannot reach the browser either: it runs in the same process as AIMMS.
Prerequisites
AIMMS 26.8 or later on Windows, with the Python-Bridge set up as described in Nice to Meet You pyaimms from Python-Bridge.
A
.wavfile.winsoundplays WAV files only.
winsound is part of the Python standard library on Windows, so you don’t need to add a dependency
to pyproject.toml.
To follow along, download the example project (AIMMS 26.8), which includes a short bird song as sound file:
719_playing_a_sound.zip.
Steps in the Python File
Place play_sound.py in the PythonScripts subfolder of your project:
1import os
2import winsound
3
4
5def play_wav(filename: str):
6 """Plays a WAV file without waiting for it to finish."""
7 if not os.path.isfile(filename):
8 raise FileNotFoundError(f"Sound file not found: {os.path.abspath(filename)}")
9 winsound.PlaySound(filename, winsound.SND_FILENAME | winsound.SND_ASYNC)
Remarks:
Lines 7-8:
winsounddoes not report a missing file; you would hear the Windows default sound, or nothing. This check gives a clear error message instead, which AIMMS shows in its error messages.Line 9:
SND_ASYNCreturns directly, so AIMMS continues while the sound plays. Without it, AIMMS waits until the sound has finished.
Steps in the AIMMS Project
Load the Python file once, for example in PostMainInitialization:
1py::run_python_script("PythonScripts/play_sound.py");
To play a sound, put the file name in a string parameter, for example sp_soundFile, and pass it to the Python function:
1sp_soundFile :="Sounds/birds.wav";
2py::run_python_statement(formatString("play_wav(r\"%s\")", sp_soundFile));
The r before the string makes it a raw Python string, so backslashes in a Windows path are not read as
escape characters. The file name is relative to the AIMMS project folder.
See also
Python documentation of winsound