LazyCodet

a

19:45:54 16/2/2025 - 0 views -
Programming

How to Play Audio in Windows Using Git Bash or Bash Script

Playing audio files from a Bash script on Windows may not be as straightforward as on Linux, where tools like aplay or mpg123 are readily available. However, with Git Bash and PowerShell, you can easily trigger audio playback.

Playing Audio with PowerShell in Git Bash

Git Bash, which provides a Unix-like terminal on Windows, does not include built-in support for playing audio. However, since Git Bash can execute PowerShell commands, we can leverage PowerShell’s Media.SoundPlayer to play a .wav file.

Here’s a simple one-liner that plays a system sound (chimes.wav) using Git Bash:

history -a && (powershell -c "(New-Object Media.SoundPlayer C:/Windows/Media/chimes.wav).PlaySync();" &)

Breakdown of the Command

  • history -a → Saves the current command history to the .bash_history file (optional).
  • (powershell -c "...") → Invokes PowerShell within Git Bash.
  • New-Object Media.SoundPlayer C:/Windows/Media/chimes.wav → Creates a new SoundPlayer object for the specified WAV file.
  • .PlaySync(); → Plays the sound and waits for it to finish before continuing execution.
  • & → Runs the command in the background so the terminal remains responsive.

Customizing the Command

To play a different sound, replace C:/Windows/Media/chimes.wav with the full path of your desired .wav file:

powershell -c "(New-Object Media.SoundPlayer 'C:/path/to/your/audio.wav').PlaySync();"

For non-WAV formats (e.g., MP3 or FLAC), you’ll need an alternative method, such as using wmplayer.exe (Windows Media Player) or mpg123 if installed.

Creating a Bash Script for Audio Playback

To make this more reusable, save the command in a Bash script (play-audio.sh):

#!/bin/bash
AUDIO_PATH="C:/Windows/Media/chimes.wav"
powershell -c "(New-Object Media.SoundPlayer '$AUDIO_PATH').PlaySync();"

Then, grant execution permissions and run the script:

chmod +x play-audio.sh
./play-audio.sh

Conclusion

Using PowerShell within Git Bash, you can easily play .wav files without installing additional software. This approach is useful for notifications, automation, or simple alerts in your Bash scripts.

For more advanced audio control, consider using third-party tools like VLC (vlc.exe), FFmpeg, or Windows Media Player, depending on your needs.

References

https://superuser.com/a/1677417