raspberrypi / picamera2

New libcamera based python library
BSD 2-Clause "Simplified" License
897 stars 190 forks source link

[solved] How to add audio from USB Microfon ? #1114

Open FredFeuerstein0815 opened 2 months ago

FredFeuerstein0815 commented 2 months ago

How can i set the audio source to USB Microfon ?

Hardware: Raspberry Pi Zero Bookworm with OV5647 Raspberry Pi 4 Bullseye with OV5647 Microfon: Pi Zero: Input Device id 0 - USB Device 0x46d:0x819: Audio (hw:1,0) Input Device id 1 - USB Audio Device: - (hw:2,0)

Pi4: 0014:0d8c C-Media Electronics Inc. USB Audio Device

, audio=True seems not to be enough.

For now my Code is:

!/usr/bin/python3

from libcamera import Transform from picamera2.outputs import FfmpegOutput from datetime import datetime from time import sleep from picamera2 import Picamera2 from picamera2.encoders import H264Encoder

Picamera2.set_logging(Picamera2.DEBUG) picam2 = Picamera2() video_config = picam2.create_video_configuration(main={"size": (1024, 768)}, transform=Transform(hflip=True, vflip=True)) picam2.configure(videoconfig) encoder = H264Encoder(3000000) jetzt = str((datetime.now().strftime('%Y-%m-%d%H:%M:%S'))) output = FfmpegOutput("{}.mp4".format(jetzt), audio=True) picam2.start_recording(encoder, output) sleep(10) picam2.stop_recording()

Thanks for help.

FredFeuerstein0815 commented 2 months ago

Ok, here is the trick. You have to edit ffmpegoutput.py in /usr/lib/python3/dist-packages/picamera2/outputs/ Here you can set the audio_device="", but it does not work with audio_device="hw:3,0" or else. You have to use this to get the list of sources on Bullseye:

pacmd list-sources | grep -e 'index:' -e device.string -e 'name:'

If you have Bookworm and there is no pulseaudio running you can detect your input device with:

pactl list | grep alsa_input

In my case of my Pi4 it is:

index: 0 name: device.string = "3"

So i have to put alsa_input.usb-C-Media_Electronics_Inc._USB_Audio_Device-00.mono-fallback in audio_device="":

def __init__(self, output_filename, audio=False, audio_device="alsa_input.usb-C-Media_Electronics_Inc._USB_Audio_Device-00.mono-fallback", audio_sync=-0.3,
             audio_samplerate=48000, audio_codec="aac", audio_bitrate=128000, pts=None):

But you also have to change in Bullseye below self.ffmpeg.wait() to self.ffmpeg.terminate() or it will never stop recording.

    def stop(self):
        super().stop()
        if self.ffmpeg is not None:
            self.ffmpeg.stdin.close()  # FFmpeg needs this to shut down tidily
#            self.ffmpeg.wait()
            self.ffmpeg.terminate()
            self.ffmpeg = None

Now it works as expected.