How to stream audio using FFMPEG?

There are two solutions I can visualize for this scenario:

  • Saving the file to a remote computer
  • Having a live stream broadcast so a remote computer can receive the audio

Saving the file

This is probably the easiest method. Allow the stream to finish recording then copy it to a predetermined location on the network. This script should fit the bill:

#!/bin/bash
#
ffmpeg -f avfoundation -i ":1" -t 10 audiocapture.mp3
scp audiocapture.mp3 user@host:/foo/bar/audiocapture.mp3

exit 0

The script doesn't do any error checking of any kind but, will record from the microphone, then when finished it will copy it via SCP (secure copy) to a remote computer. To make this work, you need to set up SSH Keys to facilitate a non-interactive login.

Stream in real time

The other method, is to broadcast the audio via TCP via a point-to-point connection. Using the same input from the previous answer, we just change the output to a network stream:

$ ffmpeg -f avfoundation -i ":1" -t 10 -f mpegts "tcp://remote_host_or_IP_:port"

Where....

  • -f is the transport format; in this case mpegts (MPEG Transport Stream)
  • tcp://remote_host_or_IP_:port is the URI value of the remote computer's hostname/IP address and port number it will be listening on.

Set remote computer to "listen"

Using ffplay the remote computer can be set to receive the stream (I used Windows 10 for this part, but will work in macOS/Windows/BSD/Linux)

Issue the command

ffplay -i tcp://local_host_or_IP_addr:port?listen -hide_banner

Where....

  • -i defines the input stream
  • local_host_or_IP_addr:port is the IP address or hostname and the TCP port of the computer that's listening (not the computer that's streaming).
  • ?listen is required to put it into "listen mode" otherwise it will time out if the stream is not there.

Below is an example done in Windows 10 receiving the stream from a macOS host's microphone. The IP address of the Windows 10 machine is 10.0.0.123 and I am broadcasting on port 1234.

C:\Users\allan\Desktop\ffmpeg>ffplay -i tcp://10.0.0.123:1234?listen -hide_banner

    nan    :  0.000 fd=   0 aq=    0KB vq=    0KB sq=    0B f=0/0

Once it begins to receive the broadcast, the values above will change and a player "visualization" window will open up.

Input #0, mpegts, from 'tcp://10.0.0.123:1234?listen':B f=0/0
384 kb/s    nan    :  0.000 fd=   0 aq=    0KB vq=    0KB sq=    0B f=0/0
  Program 1   0.000 fd=   0 aq=    0KB vq=    0KB sq=    0B f=0/0
    Metadata: 0.000 fd=   0 aq=    0KB vq=    0KB sq=    0B f=0/0
Service01    nan    :  0.000 fd=   0 aq=    0KB vq=    0KB sq=    0B f=0/0       0B f=0/0
FFmpeg    nan    :  0.000 fd=   0 aq=    0KB vq=    0KB sq=    0B f=0/0   sq=    0B f=0/0
    Stream #0:0[0x100]: Audio: mp2 ([3][0][0][0] / 0x0003), 44100 Hz, stereo, fltp, 384 kb/s
  11.35 M-A:  0.000 fd=   0 aq=    0KB vq=    0KB sq=    0B f=0/0

It will continue to "listen" until the process is killed.