Skip to content

Instantly share code, notes, and snippets.

@Deliquescence
Last active December 14, 2020 01:33
Show Gist options
  • Save Deliquescence/d4ff11511da45b972322efa02b985ff2 to your computer and use it in GitHub Desktop.
Save Deliquescence/d4ff11511da45b972322efa02b985ff2 to your computer and use it in GitHub Desktop.
Record linux desktop audio using script which can be set as keybind
#!/bin/bash
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# The file TaskCompletedSound.wav is from the project ShareX,
# which is licensed under the GNU General Public License v3.0.
# https://github.com/ShareX/ShareX/blob/a06ba651ca452871a13a12f4361370a025a38042/ShareX/Resources/TaskCompletedSound.wav
# pactl list short sources
sourceName=alsa_output.usb-Schiit_Audio_Schiit_Modi_3-00.analog-stereo.monitor
sourceChannels=2
sourceRate=44100
outputDir=/tmp/audioRecordHotkey
tempRecordFile="$outputDir/temp.wav"
pidFile="$outputDir/pid"
mkdir -p $outputDir
if [ -f $pidFile ]; then
# Get PID of the ffmpeg which is recording
pid=$(cat $pidFile)
rm $pidFile
# Tell ffmpeg to stop
kill -2 $pid
# Wait until ffmpeg has cleanly stopped
tail --pid=$pid -f /dev/null
if [ -f $tempRecordFile ]; then
# Create output file from temporary
timestamp=`date +%F_%T.%N`
outputFile="$outputDir/$timestamp.mp3"
# Remove silence from beginning/end and normalize volume
ffmpeg -i $tempRecordFile -af silenceremove=1:0:-80dB,areverse,silenceremove=1:0:-80dB,areverse,loudnorm -y $outputFile
# Copy the file path to clipboard so it can be pasted
# Uncomment "-sel c" to use Ctrl C clipboard instead of middle click
echo "file:$outputFile" | xclip -t text/uri-list #-sel c
rm $tempRecordFile
# Play sound
currentDir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
mpv "$currentDir/TaskCompletedSound.wav"
fi
else
# Start recording
ffmpeg -f pulse -ac $sourceChannels -ar $sourceRate -i $sourceName -ar 44100 -q:a 1 -y $tempRecordFile &
# Save PID of ffmpeg
echo $! > $pidFile
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment