Skip to content

Instantly share code, notes, and snippets.

@zumpchke
Forked from GusAntoniassi/README.md
Last active September 24, 2021 12:02
Show Gist options
  • Save zumpchke/4eacefdfffa0da6e6b4270e9b516b403 to your computer and use it in GitHub Desktop.
Save zumpchke/4eacefdfffa0da6e6b4270e9b516b403 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=44100 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."
#while true; do
#ffmpeg -re -i "$INPUT_FILE" -f s16le -ar 44100 -ac 1 - > "$VIRTMIC_PATH"
snapclient -h 10.0.0.24 --logsink null --player file > "$VIRTMIC_PATH"
#ffmpeg -re -i "$INPUT_FILE" -f s16le -ar 44100 -ac 1 - > "$VIRTMIC_PATH"
#done
cleanup
This file has been truncated, but you can view the full file.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment