撰寫: 2022/1/25

發佈: 2022/2/16

Raspberry Pi使用USB Audio裝置

為何要在Raspberry Pi上使用USB audio裝置呢?當你發現Raspberry Pi並沒有audio input端口來接麥克風,或甚至Raspberry Pi Zeroaudio output端口都沒有的時候,你就會想辦法在Raspberry Pi上加上USB audio裝置來達到audio input/output的目的。

目前在Raspberry Pi有相當多的USB audio裝置可以使用,只要是因為它們都使用 “C-Media” 晶片。

再加上新版的Raspbian作業系統已經支援Plug-n-Plug,所以只需要將USB audio裝置插入,輸入以下的命令檢查有哪一些USB裝置:

lsusb

可以看到以下回應:

Bus 001 Device 005: ID 8086:0808 Intel Corp.

Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter

Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp.

Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

其中的Device 005就是我新插入的USB audio裝置

 

可以再以下列的命令檢查所有Message有關C-Media晶片:

dmesg | grep C-Media

搜尋結果如下:

[    2.224342] usb 1-1.5: Manufacturer: C-Media Electronics Inc.     

[    2.230660] input: C-Media Electronics Inc.       USB PnP Sound Device as /devices/platform/soc/3f980000.usb/usb1/1-1/1-1.5/1-1.5:1.3/0003:8086:0808.0001/input/input0

[    2.296082] hid-generic 0003:8086:0808.0001: input,hidraw0: USB HID v1.00 Device [C-Media Electronics Inc.       USB PnP Sound Device] on usb-3f980000.usb-1.5/input3

[   20.634107] usb 1-1.5: Manufacturer: C-Media Electronics Inc.     

[   20.670453] input: C-Media Electronics Inc.       USB PnP Sound Device as /devices/platform/soc/3f980000.usb/usb1/1-1/1-1.5/1-1.5:1.3/0003:8086:0808.0002/input/input1

[   20.736492] hid-generic 0003:8086:0808.0002: input,hidraw0: USB HID v1.00 Device [C-Media Electronics Inc.       USB PnP Sound Device] on usb-3f980000.usb-1.5/input3

表示確實有C-Media晶片USB audio裝置載入到系統中,所以就可以再以下列命令檢查所有註冊在系統中的所有audio播放裝置:

aplay -l

出現所有註冊在系統中的所有audio裝置如下:

**** List of PLAYBACK Hardware Devices ****

card 0: ALSA [bcm2835 ALSA], device 0: bcm2835 ALSA [bcm2835 ALSA]

  Subdevices: 8/8

  Subdevice #0: subdevice #0

  Subdevice #1: subdevice #1

  Subdevice #2: subdevice #2

  Subdevice #3: subdevice #3

  Subdevice #4: subdevice #4

  Subdevice #5: subdevice #5

  Subdevice #6: subdevice #6

  Subdevice #7: subdevice #7

card 0: ALSA [bcm2835 ALSA], device 1: bcm2835 ALSA [bcm2835 IEC958/HDMI]

  Subdevices: 1/1

  Subdevice #0: subdevice #0

card 1: Device [USB PnP Sound Device], device 0: USB Audio [USB Audio]

  Subdevices: 1/1

  Subdevice #0: subdevice #0

其中的card 0就是Raspberry Pi原來內建的音效裝置,card 0第二個很明顯顯示HDMI的音效,所以card 0第一個應該是3.5mm音效輸出。另外card 1就是我們新插入的USB Audio裝置。

 

設定USB Audio裝置為初始的Audio裝置

我們也可以將USB Audio裝置設定為初始的Audio裝置,在Raspberry Pi Audio裝置設定在系統中的alsa.conf檔案,因為是系統檔案,所有權限保護設定,要修改它需要super user權限,所以必須以super user方式修改:

sudo nano /usr/share/alsa/alsa.conf

在文中找到以下的訊息:

defaults.ctl.card 0

defaults.pcm.card 0

修改成為剛才找到的USB Audio裝置 card 1

defaults.ctl.card 1

defaults.pcm.card 1

採用[CTRL-X], [Y], [ENTER]方式,儲存檔案並回到命令欄模式。

 

或先將alsa.conf檔案拷貝在pi路徑,採用Text Editor編輯,在文中找到以下的訊息:

defaults.ctl.card 0

defaults.pcm.card 0

修改成為剛才找到的USB Audio裝置 card 1

defaults.ctl.card 1

defaults.pcm.card 1

儲存檔案離開並回到命令欄模式,以super user拷貝到/usr/share/alsa/路徑下。

 

設定USB Audio裝置聲音大小

Raspberry Pi 中可以alsamixer來設定Audio裝置聲音大小,在系統終端機Terminal命令欄輸入下列命令:

alsamixer

終端機Terminal會出現如下的畫面可以設定 “Speaker”, “Mic” and “Auto Gain Control”

 

 

 

 

 

 

F4鍵就可以切換到Capture

 

或按F5鍵兩者同時出現如下:

在此可以用左右鍵在不同的 “Speaker”, “Mic”裝置通道間切換,用上下鍵可以改變Gain大小數值,在此特別要注意Mic裝置下方default顯示|MM|表示該裝置初始狀態是設為Mute靜音,因為我們要使用麥克風收音,所以可以按”M” 鍵改變切換為啟動模式。

 

另外Rasbain在版本可以直接在偏好設定中設定音效裝置,如下圖所示:

進入畫面因為初始設定為Raspberry Pi內建的BCM2835所以沒有可選的,可在音效卡欄位選取USB PnP Sound Device如下:

選取後就會出現與alsamixer類似同樣的設定畫面如下,照剛才方式設定就可以了。

 

不過此Audio Device設定功能在最新版BullseyeBuster中被移除了,所以還是要以alsamixer來設定Audio裝置聲音大小,在如圖所示:

不過選擇音源可以直接在右上方喇叭圖示按右鍵就會出現選單可以選取。

測試喇叭Speak聲音輸出

將耳機或喇叭插入USB Audio裝置聲音輸出端,你就可以用Raspberry Pi 上的speaker-test公用程式來測試喇叭輸出:

speaker-test

正常喇叭會出現雜訊的聲音及以下的訊息:

speaker-test 1.0.28

Playback device is default

Stream parameters are 48000Hz, S16_LE, 1 channels

Using 16 octaves of pink noise

Rate set to 48000Hz (requested 48000Hz)

Buffer size range from 2048 to 16384

Period size range from 1024 to 1024

Using max buffer size 16384

Periods = 4

was set period_size = 1024

was set buffer_size = 16384

 0 - Front Left

Time per period = 2.665282

 0 - Front Left

可以發現目前只有左聲道輸出,而且只有pink noise雜訊的聲音一直重複。離開測試可以按CTRL-Z來結束。

至於如何用聲音方式來測雙聲道,可以輸入speaker-test -h來查看如何使用如下:

speaker-test 1.0.28

Usage: speaker-test [OPTION]...

-h,--help help

-D,--device             playback device

-r,--rate  stream rate in Hz

-c,--channels          count of channels in stream

-f,--frequency        sine wave frequency in Hz

-F,--format             sample format

-b,--buffer              ring buffer size in us

-p,--period             period size in us

-P,--nperiods         number of periods

-t,--test   pink=use pink noise, sine=use sine wave, wav=WAV file

-l,--nloops              specify number of loops to test, 0 = infinite

-s,--speaker           single speaker test. Values 1=Left, 2=right, etc

-w,--wavfile           Use the given WAV file as a test sound

-W,--wavdir           Specify the directory containing WAV files

-m,--chmap            Specify the channel map to override

-X,--force-frequency             force frequencies outside the 30-8000hz range

Recognized sample formats are: S8 S16_LE S16_BE FLOAT_LE S32_LE S32_BE

 

可輸入以下命令來進行雙聲道及1kHz弦波測試如下:

speaker-test -c2 -t sine -f 1000

就會有左右聲道切換tone的聲音,訊息如下:

speaker-test 1.0.28

Playback device is default

Stream parameters are 48000Hz, S16_LE, 2 channels

Sine wave rate is 1000.0000Hz

Rate set to 48000Hz (requested 48000Hz)

Buffer size range from 2048 to 16384

Period size range from 1024 to 1024

Using max buffer size 16384

Periods = 4

was set period_size = 1024

was set buffer_size = 16384

 0 - Front Left

 1 - Front Right

Time per period = 5.657501

 0 - Front Left

 1 - Front Right

 

若要測試音效,可以下載簡單的WAV音效檔如下:

wget https://www.kozco.com/tech/piano2.wav

採用aplay進行播放:

aplay piano2.wav

Playing WAVE 'piano2.wav' : Signed 16 bit Little Endian, Rate 48000 Hz, Stereo

以下是補充aplay命令使用說明:

Usage: aplay [OPTION]... [FILE]...

-h, --help                              help

   --version                         print current version

-l, --list-devices                    list all soundcards and digital audio devices

-L, --list-pcms                       list device names

-D, --device=NAME              select PCM by name

-q, --quiet                            quiet mode

-t, --file-type TYPE              file type (voc, wav, raw or au)

-c, --channels=#                   channels

-f, --format=FORMAT          sample format (case insensitive)

-r, --rate=#                           sample rate

-d, --duration=#                  interrupt after # seconds

-M, --mmap                         mmap stream

-N, --nonblock                     nonblocking mode

-F, --period-time=#              distance between interrupts is # microseconds

-B, --buffer-time=#              buffer duration is # microseconds

    --period-size=#             distance between interrupts is # frames

    --buffer-size=#              buffer duration is # frames

-A, --avail-min=#                 min available space for wakeup is # microseconds

-R, --start-delay=#               delay for automatic PCM start is # microseconds

                        (relative to buffer size if <= 0)

-T, --stop-delay=#                delay for automatic PCM stop is # microseconds from xrun

-v, --verbose                        show PCM structure and setup (accumulative)

-V, --vumeter=TYPE             enable VU meter (TYPE: mono or stereo)

-I, --separate-channels       one file for each channel

-i, --interactive              allow interactive operation from stdin

-m, --chmap=ch1,ch2,..     Give the channel map to override or follow

    --disable-resample     disable automatic rate resample

    --disable-channels      disable automatic channel conversions

    --disable-format       disable automatic format conversions

    --disable-softvol         disable software volume control (softvol)

    --test-position          test ring buffer position

    --test-coef=#          test coefficient for ring buffer position (default 8)

                       expression for validation is: coef * (buffer_size / 2)

    --test-nowait          do not wait for ring buffer - eats whole CPU

    --max-file-time=#       start another output file when the old file has recorded

                        for this many seconds

    --process-id-file         write the process ID here

    --use-strftime         apply the strftime facility to the output file name

    --dump-hw-params   dump hw_params of the device

    --fatal-errors           treat all errors as fatal

Recognized sample formats are: S8 U8 S16_LE S16_BE U16_LE U16_BE S24_LE S24_BE U24_LE U24_BE S32_LE S32_BE U32_LE U32_BE FLOAT_LE FLOAT_BE FLOAT64_LE FLOAT64_BE IEC958_SUBFRAME_LE IEC958_SUBFRAME_BE MU_LAW A_LAW IMA_ADPCM MPEG GSM SPECIAL S24_3LE S24_3BE U24_3LE U24_3BE S20_3LE S20_3BE U20_3LE U20_3BE S18_3LE S18_3BE U18_3LE U18_3BE G723_24 G723_24_1B G723_40 G723_40_1B DSD_U8 DSD_U16_LE

Some of these may not be available on selected hardware

The available format shortcuts are:

-f cd (16 bit little endian, 44100, stereo)

-f cdr (16 bit big endian, 44100, stereo)

-f dat (16 bit little endian, 48000, stereo)

 

測試麥克風Microphone聲音輸入

麥克風在Raspberry pi系統中可以arecord -l命令檢查所有註冊在系統中的所有audio錄音裝置:

arecord -l

**** List of CAPTURE Hardware Devices ****

card 1: Device [USB PnP Sound Device], device 0: USB Audio [USB Audio]

  Subdevices: 1/1

  Subdevice #0: subdevice #0

在此只能看到card 1一個裝置,這就是USB audio裝置帶出來的,因為Raspberry pi初始並沒有錄音裝置。

要測試錄音可以下列命令錄一段5secs的錄音檔:

arecord --format=S16_LE --duration=5 --rate=16000 --file-type=wav test.wav

Recording WAVE 'test.wav' : Signed 16 bit Little Endian, Rate 16000 Hz, Mono

記得用Ctrl-Z中斷,不然就會不斷5秒產生一個檔!

Raspbian早期版本(Pixel 3)可能設定音效卡不支援低取樣率16000,這時可以採用建議的44100高取樣率,這測試的命令如下:

arecord --format=S16_LE --duration=5 --rate=44100 --file-type=wav test.wav

播放此檔就可用前面的aplay命令如下:

aplay --format=S16_LE --rate=16000 test.wav

或是:

aplay --format=S16_LE --rate=44100 test.wav

以下是補充arecord命令使用說明:

Usage: arecord [OPTION]... [FILE]...

-h, --help                help

  --version                print current version

-l, --list-devices                             list all soundcards and digital audio devices

-L, --list-pcms                             list device names

-D, --device=NAME                      select PCM by name

-q, --quiet                quiet mode

-t, --file-type TYPE                         file type (voc, wav, raw or au)

-c, --channels=#           channels

-f, --format=FORMAT     sample format (case insensitive)

-r, --rate=#               sample rate

-d, --duration=#           interrupt after # seconds

-M, --mmap                          mmap stream

-N, --nonblock          nonblocking mode

-F, --period-time=#         distance between interrupts is # microseconds

-B, --buffer-time=#         buffer duration is # microseconds

    --period-size=#        distance between interrupts is # frames

    --buffer-size=#         buffer duration is # frames

-A, --avail-min=#           min available space for wakeup is # microseconds

-R, --start-delay=#                          delay for automatic PCM start is # microseconds

                        (relative to buffer size if <= 0)

-T, --stop-delay=#          delay for automatic PCM stop is # microseconds from xrun

-v, --verbose             show PCM structure and setup (accumulative)

-V, --vumeter=TYPE      enable VU meter (TYPE: mono or stereo)

-I, --separate-channels                      one file for each channel

-i, --interactive                             allow interactive operation from stdin

-m, --chmap=ch1,ch2,..     Give the channel map to override or follow

    --disable-resample     disable automatic rate resample

    --disable-channels      disable automatic channel conversions

    --disable-format       disable automatic format conversions

    --disable-softvol         disable software volume control (softvol)

    --test-position          test ring buffer position

    --test-coef=#          test coefficient for ring buffer position (default 8)

                        expression for validation is: coef * (buffer_size / 2)

    --test-nowait          do not wait for ring buffer - eats whole CPU

    --max-file-time=#       start another output file when the old file has recorded

                        for this many seconds

    --process-id-file                         write the process ID here

    --use-strftime         apply the strftime facility to the output file name

    --dump-hw-params    dump hw_params of the device

    --fatal-errors           treat all errors as fatal

Recognized sample formats are: S8 U8 S16_LE S16_BE U16_LE U16_BE S24_LE S24_BE U24_LE U24_BE S32_LE S32_BE U32_LE U32_BE FLOAT_LE FLOAT_BE FLOAT64_LE FLOAT64_BE IEC958_SUBFRAME_LE IEC958_SUBFRAME_BE MU_LAW A_LAW IMA_ADPCM MPEG GSM SPECIAL S24_3LE S24_3BE U24_3LE U24_3BE S20_3LE S20_3BE U20_3LE U20_3BE S18_3LE S18_3BE U18_3LE U18_3BE G723_24 G723_24_1B G723_40 G723_40_1B DSD_U8 DSD_U16_LE

Some of these may not be available on selected hardware

The available format shortcuts are:

-f cd (16 bit little endian, 44100, stereo)

-f cdr (16 bit big endian, 44100, stereo)

-f dat (16 bit little endian, 48000, stereo)

 

另外可以進行一個回授測試

arecord --format=S16_LE --rate=16000 | aplay --format=S16_LE --rate=16000

或是

arecord --format=S16_LE --rate=44100 | aplay --format=S16_LE --rate=44100

 

後記

本文為個人學習的經驗,後續有所改進將再發文分享;本人因工作因素發文後並不會經常檢視讀者問題,對於沒法及時回覆問題敬請見諒!

若覺本文對讀者有所幫助,可回覆感想及你的分享!謝謝!

 

 

文章標籤
全站熱搜
創作者介紹
創作者 Philip4G 的頭像
Philip4G

Philip4G四眼仙機的部落格

Philip4G 發表在 痞客邦 留言(0) 人氣(789)