OSError: [Errno -9996] Invalid input device (no default output device)

I wrote a speech recognition program in python and I’m having trouble deploying it with docker container.

OSError: [Errno -9996] Invalid input device (no default output device)

I’ve researched the error the suggesstion have been to install portudio or to set up a dev/snd. I’ve implemented the suggestions and I’m still getting the above error.

Dockerfile

FROM python:3.7.9

RUN	apt-get update && apt-get install -y \
	dirmngr \
	gnupg \
	--no-install-recommends \
	&& apt-get update && apt-get install -y \
	alsa-utils \
	libgl1-mesa-dri \
	libgl1-mesa-glx \
	libpulse0 \
	xdg-utils \
	libnotify-bin \
	rtkit \
	pulseaudio \
	--no-install-recommends \
	&& rm -rf /var/lib/apt/lists/*

RUN apt-get -y update
RUN apt-get -y upgrade
RUN apt-get install -y ffmpeg

WORKDIR /usr/src/app

COPY requirements.txt ./

RUN apt-get update \
        && apt-get install libportaudio2 libportaudiocpp0 portaudio19-dev libasound-dev libsndfile1-dev -y \
        && pip install pyaudio \
    pip install --upgrade pip \
    pip install --no-cache-dir -r requirements.txt\
    pip install torch==1.4.0+cpu -f https://download.pytorch.org/whl/cpu/torch_stable.html

RUN adduser --disabled-password --gecos '' ml-api-user

ADD . .

USER ml-api-user

EXPOSE 5000

CMD ["bash", "./run.sh"]

docker-compose-yml

The applications builds and launches without any errors. The web page loads, but no sound is being recorded. I’ve mounted a soud device in the my docker-compose yml file.

version: '3.4'

services:
  common-voice:

    build: .
    image: anelso42/common-voice-app
    devices:
      - /dev/input
      - /dev/snd
      - /dev/snd:/dev/snd

    volumes:
      - .:/usr/src/app
      - /tmp/.X11-unix:/tmp/.X11-unix

    ports:
      - 5000:5000

Inside the docker container I rand the command for the dev/snd below.

$ ls /dev/snd
seq  timer

Reproduce Error

The specific code that generates the error is below.

import pyaudio

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print("* done recording")

stream.stop_stream()
stream.close()

Docker version:

$ docker version                                                                                                       
 Client:
 Version:           19.03.1
 API version:       1.40
 Go version:        go1.12.7
 Git commit:        74b1e89e8a
 Built:             Wed Jul 31 15:18:18 2019
 OS/Arch:           windows/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          19.03.12
  API version:      1.40 (minimum version 1.12)
  Go version:       go1.13.10
  Git commit:       48a66213fe
  Built:            Mon Jun 22 15:49:35 2020
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          v1.2.13
  GitCommit:        7ad184331fa3e55e52b890ea95e65ba581ae3429
 runc:
  Version:          1.0.0-rc10
  GitCommit:        dc9208a3303feef5b3839f4323d9beb36df0a9dd
 docker-init:
  Version:          0.18.0
  GitCommit:        fec3683

Docker info

$ docker info                                                                                                           
Client:
Debug Mode: false

Server:
 Containers: 1
  Running: 1
  Paused: 0
  Stopped: 0
 Images: 44
 Server Version: 19.03.12
 Storage Driver: overlay2
  Backing Filesystem: extfs
  Supports d_type: true
  Native Overlay Diff: true
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
 Swarm: inactive
 Runtimes: runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: 7ad184331fa3e55e52b890ea95e65ba581ae3429
 runc version: dc9208a3303feef5b3839f4323d9beb36df0a9dd
 init version: fec3683
 Security Options:
  seccomp
   Profile: default
 Kernel Version: 4.19.130-boot2docker
 Operating System: Boot2Docker 19.03.12 (TCL 10.1)
 OSType: linux
 Architecture: x86_64
 CPUs: 1
 Total Memory: 985.4MiB
 Name: default
 ID: XMU6:EXYC:TYQI:AIMO:PWCV:S4ER:YURW:QZHU:YWS3:XAER:BZIS:7C4G
 Docker Root Dir: /mnt/sda1/var/lib/docker
 Debug Mode: false
 Registry: https://index.docker.io/v1/
 Labels:
  provider=virtualbox
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Live Restore Enabled: false
 Product License: Community Engine

Full Error Log:

ALSA lib pulse.c:243:(pulse_connect) PulseAudio: Unable to connect: Connection refused

ALSA lib pcm_a52.c:823:(_snd_pcm_a52_open) a52 is only for playback
ALSA lib conf.c:5014:(snd_config_expand) Unknown parameters {AES0 0x6 AES1 0x82 AES2 0x0 AES3 0x2  CARD 0}
ALSA lib pcm.c:2565:(snd_pcm_open_noupdate) Unknown PCM iec958:{AES0 0x6 AES1 0x82 AES2 0x0 AES3 0x2  CARD 0}
ALSA lib pcm_hw.c:1822:(_snd_pcm_hw_open) Invalid value for card
ALSA lib pcm_hw.c:1822:(_snd_pcm_hw_open) Invalid value for card
ALSA lib pcm_hw.c:1822:(_snd_pcm_hw_open) Invalid value for card
ALSA lib pcm_hw.c:1822:(_snd_pcm_hw_open) Invalid value for card
ALSA lib pcm_usb_stream.c:486:(_snd_pcm_usb_stream_open) Invalid type for card
ALSA lib pcm_usb_stream.c:486:(_snd_pcm_usb_stream_open) Invalid type for card
ALSA lib confmisc.c:767:(parse_card) cannot find card '0'
ALSA lib conf.c:4568:(_snd_config_evaluate) function snd_func_card_driver returned error: No such file or directory
ALSA lib confmisc.c:392:(snd_func_concat) error evaluating strings
ALSA lib conf.c:4568:(_snd_config_evaluate) function snd_func_concat returned error: No such file or directory
ALSA lib confmisc.c:1246:(snd_func_refer) error evaluating name
ALSA lib conf.c:4568:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory
ALSA lib conf.c:5047:(snd_config_expand) Evaluate error: No such file or directory
ALSA lib pcm.c:2565:(snd_pcm_open_noupdate) Unknown PCM default
ALSA lib confmisc.c:767:(parse_card) cannot find card '0'
ALSA lib conf.c:4568:(_snd_config_evaluate) function snd_func_card_driver returned error: No such file or directory
ALSA lib confmisc.c:392:(snd_func_concat) error evaluating strings
ALSA lib conf.c:4568:(_snd_config_evaluate) function snd_func_concat returned error: No such file or directory
ALSA lib confmisc.c:1246:(snd_func_refer) error evaluating name
ALSA lib conf.c:4568:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory
ALSA lib conf.c:5047:(snd_config_expand) Evaluate error: No such file or directory
ALSA lib pcm.c:2565:(snd_pcm_open_noupdate) Unknown PCM default
ALSA lib confmisc.c:767:(parse_card) cannot find card '0'
ALSA lib conf.c:4568:(_snd_config_evaluate) function snd_func_card_driver returned error: No such file or directory
ALSA lib confmisc.c:392:(snd_func_concat) error evaluating strings
ALSA lib conf.c:4568:(_snd_config_evaluate) function snd_func_concat returned error: No such file or directory
ALSA lib confmisc.c:1246:(snd_func_refer) error evaluating name
ALSA lib conf.c:4568:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory
ALSA lib conf.c:5047:(snd_config_expand) Evaluate error: No such file or directory
ALSA lib pcm.c:2565:(snd_pcm_open_noupdate) Unknown PCM dmix
[2020-08-30 23:19:26 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:8)

Exception in thread Thread-3:
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/usr/local/lib/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/local/lib/python3.7/site-packages/socketio/server.py", line 682, in _handle_event_internal
    r = server._trigger_event(data[0], namespace, sid, *data[1:])
  File "/usr/local/lib/python3.7/site-packages/socketio/server.py", line 711, in _trigger_event
    return self.handlers[namespace][event](*args)
  File "/usr/local/lib/python3.7/site-packages/flask_socketio/__init__.py", line 283, in _handler
    *args)
  File "/usr/local/lib/python3.7/site-packages/flask_socketio/__init__.py", line 713, in _handle_event
    ret = handler(*args)
  File "/usr/src/app/commonvoice/api/app.py", line 90, in run_audio_stream
    stream_callback=callback,
  File "/usr/local/lib/python3.7/site-packages/pyaudio.py", line 750, in open
    stream = Stream(self, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/pyaudio.py", line 441, in __init__
    self._stream = pa.open(**arguments)
OSError: [Errno -9996] Invalid input device (no default output device)

Maybe the sound card is already accessed and blocked by your host. You find some detailed instructions about sound in containers at https://github.com/mviereck/x11docker/wiki/Container-sound:-ALSA-or-Pulseaudio.

I made a few edits to the docker compose and Docker file to take reflect post you sent me to. but i’m still gettting a similar errror:

Dockerfile

FROM python:3.7.8

ARG DEBIAN_FRONTEND=noninteractive

RUN apt-get update -qq \
 && apt-get install -qqy --no-install-recommends \
      ffmpeg \
      libportaudio2 \
      libportaudiocpp0 \
      libsndfile1-dev \
      portaudio19-dev \
      pulseaudio \
 && rm -rf /var/lib/apt/lists/*

RUN pip3 install --no-cache-dir pyaudio
RUN pip3 install --no-cache-dir torch==1.4.0+cpu -f https://download.pytorch.org/whl/cpu/torch_stable.html

RUN addgroup --gid 1000 ml \
 && adduser --gecos "" \
      --home /usr/src/app \
      --shell /bin/bash \
      --uid 1000 \
      --gid 1000 \
      --disabled-password \
      ml \
 && adduser ml adm \
 && adduser ml audio \
 && adduser ml pulse \
 && adduser ml voice

RUN mkdir -p /run/user/1000 \
 && chown ml:ml /run/user/1000

WORKDIR /usr/src/app

USER ml

RUN mkdir -p .local/bin .config .cache

ENV PATH="/usr/src/app/.local/bin:$PATH"

COPY --chown=ml:ml . .

RUN pip3 install --no-cache-dir -r requirements.txt

ENTRYPOINT /usr/src/app/run.sh

Docker Compose yaml

version: '3.7'

services:
  common-voice:
    build: .
    image: anelso42/common-voice-app
    devices:
      - /dev/snd
    environment:
#      - ALSA_PCM=usbstream:CARD=StargazerMicrop
      - PORT=${PORT:-5000}
      - XDG_RUNTIME_DIR=/run/user/1000
      - ALSA_CARD=Generic
    volumes:
      - $HOME/.config/pulse:/usr/src/app/.config/pulse
#      - /etc/machine-id:/etc/machine-id:ro
      - /run/user/1000/pulse:/run/user/1000/pulse:ro
    ports:
      - 5000:${PORT:-5000}

Error message:

INFO:engineio.server:ad4ad9860a1243a28c544de734c52360: Received packet MESSAGE data 2["audio-streaming",{}]
INFO:socketio.server:received event "audio-streaming" from ad4ad9860a1243a28c544de734c52360 [/]
192.168.99.1 - - [29/Sep/2020:07:37:35 +0000] "POST /socket.io/?EIO=3&transport=polling&t=NJOovPw&sid=ad4ad9860a1243a28c544de734c52360 HTTP/1.1" 200 2 "http://192.168.99.100:5000/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Kitematic/0.17.7 Chrome/59.0.3071.115 Electron/1.8.8 Safari/537.36"
Failed to create secure directory (/run/user/1000/pulse): Read-only file system
Failed to create secure directory (/run/user/1000/pulse): Read-only file system
Failed to create secure directory (/run/user/1000/pulse): Read-only file system
[2020-09-29 07:38:05 +0000] [6] [CRITICAL] WORKER TIMEOUT (pid:120)
Exception in thread Thread-2:
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/usr/local/lib/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/src/app/.local/lib/python3.7/site-packages/socketio/server.py", line 682, in _handle_event_internal
    r = server._trigger_event(data[0], namespace, sid, *data[1:])
  File "/usr/src/app/.local/lib/python3.7/site-packages/socketio/server.py", line 711, in _trigger_event
    return self.handlers[namespace][event](*args)
  File "/usr/src/app/.local/lib/python3.7/site-packages/flask_socketio/__init__.py", line 283, in _handler
    *args)
  File "/usr/src/app/.local/lib/python3.7/site-packages/flask_socketio/__init__.py", line 713, in _handle_event
    ret = handler(*args)
  File "/usr/src/app/commonvoice/api/app.py", line 91, in run_audio_stream
    stream_callback=callback,
  File "/usr/local/lib/python3.7/site-packages/pyaudio.py", line 750, in open
    stream = Stream(self, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/pyaudio.py", line 441, in __init__
    self._stream = pa.open(**arguments)
OSError: [Errno -9996] Invalid input device (no default output device)

I solve this problem in ubuntu 20, using python:3 docker image, doing next:

In Dockerfile

RUN apt-get install -y pulseaudio

In docker run command

--device /dev/snd \
-e PULSE_SERVER=unix:${XDG_RUNTIME_DIR}/pulse/native \
-v ${XDG_RUNTIME_DIR}/pulse/native:${XDG_RUNTIME_DIR}/pulse/native \
-v ~/.config/pulse/cookie:/root/.config/pulse/cookie \
-v /media/dyan/project/projects/voice/:/data/voice \

Example:

docker run -it --rm \
		 --device /dev/snd \
		 -e PULSE_SERVER=unix:${XDG_RUNTIME_DIR}/pulse/native \
		 -v ${XDG_RUNTIME_DIR}/pulse/native:${XDG_RUNTIME_DIR}/pulse/native \
		 -v ~/.config/pulse/cookie:/root/.config/pulse/cookie \
		 -v /media/dyan/project/projects/voice/:/data/voice \
		--name python-speech-recognition python-speech-recognition-app