pythonlinuxsubprocessespeak

subprocess.call can not send stdout to ffmpeg


My code is python. It call espeak command to generate .wav audio. Then call ffmpeg to convert wav to mp3.

But this command can not send stdout from espeak to ffmpeg via subprocess.call of python:

espeak -f myfile --stdout | ffmpeg -i - final.mp3

The example:

subprocess.call(["espeak", "test text to speak", "--stdout", "|"]+("ffmpeg -i - -vn -y -ar 22050 -ac 1 -ab 16k -af volume=2 -f mp3 mp3OutFile.mp3").split(" "))

What is the mistake? How can I do?


Solution

  • The pipeline you wrote is handled by the shell, and won't work (as written) unless you use shell=True. Instead of doing that, you should construct the pipeline in Python, which is pretty simple with subprocess:

    p1 = subprocess.Popen(['espeak', '-f', 'myfile', '--stdout'], stdout=subprocess.PIPE)
    p2 = subprocess.Popen(['ffmpeg', '-i', '-', 'final.mp3'], stdin=p1.stdout)
    p1.stdout.close()  # pipe is already attached to p2, and unneeded in this process
    p2.wait()
    p1.wait()