Skip to content

Instantly share code, notes, and snippets.

@GusAntoniassi
Created May 14, 2020 00:50
Show Gist options
  • Save GusAntoniassi/c994dc5fc470f5910b61e4d238a6cccf to your computer and use it in GitHub Desktop.
Save GusAntoniassi/c994dc5fc470f5910b61e4d238a6cccf to your computer and use it in GitHub Desktop.
Play audio files on your microphone with ffmpeg

play-audio-mic.sh

This script was adapted to allow you to play audio files through your microphone input. It does so by creating a virtual microphone and piping an audio file to it.

The work was mostly done in this StackOverflow answer, I just adapted it to use ffmpeg and add a trap to cleanup on exit.

Requirements:

  • ffmpeg
  • Bash
  • PulseAudio/pactl
#!/bin/bash
# This script will create a virtual microphone for PulseAudio to use and set it as the default device.
# Adapted from: https://stackoverflow.com/a/43553706/2272346
INPUT_FILE=$1
VIRTMIC_PATH=/tmp/virtmic
function cleanup() {
pactl unload-module module-pipe-source
rm -f "$HOME"/.config/pulse/client.conf
}
# Load the "module-pipe-source" module to read audio data from a FIFO special file.
echo "Creating virtual microphone."
pactl load-module module-pipe-source source_name=virtmic file=$VIRTMIC_PATH format=s16le rate=16000 channels=1
trap cleanup EXIT
# Set the virtmic as the default source device.
echo "Set the virtual microphone as the default device."
pactl set-default-source virtmic
# Create a file that will set the default source device to virtmic for all
# PulseAudio client applications.
echo "default-source = virtmic" > "$HOME"/.config/pulse/client.conf
# Write the audio file to the named pipe virtmic. This will block until the named pipe is read.
echo "Writing audio file to virtual microphone."
ffmpeg -re -i "$INPUT_FILE" -f s16le -ar 16000 -ac 1 - > "$VIRTMIC_PATH"
cleanup
@daniel-pg
Copy link

daniel-pg commented Feb 16, 2023

@AggamR The cleanup() function is executed twice: first at line 33, and then a second time when the script traps the EXIT pseudo-signal. That's why it will error, because the script will try to unload the module twice.

Fix: Just delete line 33.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment