Can I interact with the output of the OSX `say` command in a bash script?

試著忘記壹切 提交于 2020-04-13 08:02:38

问题


I have the following line that I run in terminal:

say "hello, this is the computer talking" --interactive

When I run this command, the computer speaks the words in quotes and highlights the words as they are spoken. What I would like to do is get the time of each spoken word. For example:

  • 00.00 hello
  • 01.23 this
  • 01.78 is
  • 02.10 the
  • 02.70 computer
  • 03.30 talking

I am wondering if there is any way to write a bash script that would interact with the output of the line.


回答1:


Here is a Zsh script that almost does exactly what you want.

#!/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
}

Sample output:

00.00 hello
00.26 ,
00.52 this
00.65 is
00.78 the
01.36 computer
02.04 talking

If you want to convert this to bash, then floating point arithmetic needs to be done in external commands like bc, and to get a precise timestamp you would need coreutils date (timestamp=$(gdate +%s.%N)).

By the way, if you don't want to see the comma, you can just filter it out.



来源:https://stackoverflow.com/questions/33768852/can-i-interact-with-the-output-of-the-osx-say-command-in-a-bash-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!