我可以在bash脚本中与OSX`say`命令的输出进行交互吗?

use*_*510 3 macos bash terminal

我在终端中运行以下行:

say "hello, this is the computer talking" --interactive
Run Code Online (Sandbox Code Playgroud)

当我运行此命令时,计算机会说出带引号的单词,并在说出单词时突出显示这些单词。我想做的是获取每个口语的时间。例如:

  • 00.00你好
  • 01.23这个
  • 01.78是
  • 02.10
  • 02.70电脑
  • 03.30交谈

我想知道是否有任何方法可以编写与行的输出进行交互的bash脚本。

4ae*_*1e1 5

这是一个Zsh脚本,几乎可以完全满足您的要求。

#!/bin/zsh
zmodload zsh/datetime
say --interactive "hello, this is the computer talking" | {
    counter=0
    while IFS= read -r -d $'\r' line; do
        (( counter++ )) || continue  # first line in the output of `say --interactive` suppresses the cursor; discard this line
        timestamp=$EPOCHREALTIME
        (( counter == 2 )) && offset=$timestamp  # set the timestamp of the actual first line at the offset
        (( timestamp -= offset ))
        printf '%05.2f %s\n' $timestamp ${${line%$'\e[m'*}#*$'\e[7m'}
    done
}
Run Code Online (Sandbox Code Playgroud)

样本输出:

00.00 hello
00.26 ,
00.52 this
00.65 is
00.78 the
01.36 computer
02.04 talking
Run Code Online (Sandbox Code Playgroud)

如果要将其转换为bash,则需要在外部命令(例如)中执行浮点运算bc,并且要获得准确的时间戳,您将需要coreutils datetimestamp=$(gdate +%s.%N))。

顺便说一句,如果您不想看到逗号,则可以将其过滤掉。