gpt4 book ai didi

linux - 监听音频线

转载 作者:IT王子 更新时间:2023-10-29 00:01:13 24 4
gpt4 key购买 nike

我需要在 Linux 中监控我的音频线路输入,如果播放音频,则必须录制声音并将其保存到文件中。类似于如何 motion 监控视频源。

可以用 bash 做到这一点吗?类似的东西:

#!/bin/bash

# audio device
device=/dev/audio-line-in

# below this threshold audio will not be recorded.
noise_threshold=10

# folder where recordings are stored
storage_folder=~/recordings

# run indefenitly, until Ctrl-C is pressed
while true; do
# noise_level() represents a function to determine
# the noise level from device
if noise_level( $device ) > $noise_threshold; then
# stream from device to file, can be encoded to mp3 later.
cat $device > $storage_folder/$(date +%FT%T).raw
fi;
done;

编辑:我想从这个程序中得到的流程是

 a. when noise > threshold, start recording  
b. stop recording when noise < threshold for 10 seconds
c. save recorded piece to separate file

最佳答案

SoX是声音处理的瑞士军刀。您可以使用它来分析录音。以下解决方案的唯一缺点是:

  1. 您需要将录音分成固定大小的 block
  2. 您可能会损失录制时间(由于删除/分析/重新启动录制)

因此进一步的改进可能是分析异步,尽管这会使工作复杂化。

#!/bin/bash 

record_interval=5
noise_threshold=3
storage_folder=~/recordings

exec 2>/dev/null # no default error output
while true; do
rec out.wav &
sleep $record_interval
kill -KILL %1
max_level="$(sox out.wav -n stats -s 16 2>&1|awk '/^Max\ level/ {print int($3)}')"
if [ $max_level -gt $noise_threshold ];then
mv out.wav ${storage_folder}/recording-$(date +%FT%T).wav;
else
rm out.wav
fi
done

更新:

以下解决方案使用 fifo 作为 rec 的输出。通过在此管道上使用 split 来获取 block ,应该不会损失记录时间:

#!/bin/bash 

noise_threshold=3
storage_folder=~/recordings
raw_folder=~/recordings/tmp
split_folder=~/recordings/split
sox_raw_options="-t raw -r 48k -e signed -b 16"
split_size=1048576 # 1M

mkdir -p ${raw_folder} ${split_folder}

test -a ${raw_folder}/in.raw || mkfifo ${raw_folder}/in.raw

# start recording and spliting in background
rec ${sox_raw_options} - >${raw_folder}/in.raw 2>/dev/null &
split -b ${split_size} - <${raw_folder}/in.raw ${split_folder}/piece &


while true; do
# check each finished raw file
for raw in $(find ${split_folder} -size ${split_size}c);do
max_level="$(sox $sox_raw_options ${raw} -n stats -s 16 2>&1|awk '/^Max\ level/ {print int($3)}')"
if [ $max_level -gt $noise_threshold ];then
sox ${sox_raw_options} ${raw} ${storage_folder}/recording-$(date +%FT%T).wav;
fi
rm ${raw}
done
sleep 1
done1

关于linux - 监听音频线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2613163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com