Monday, 11 February 2013

Adding an Audio Input Device

The Raspberry Pi comes with a 3.5mm analogue stereo audio output, but no input. As a radio amateur I am interested in using the Raspberry Pi to decode various digital modes, but for it to do this I need an audio input. This can be achieved by connecting a USB audio device to your Raspberry Pi (like this one supplied by Cut Price Cables).


Make sure your Raspberry Pi is turned off and insert the USB audio device into one of the USB sockets on the Raspberry Pi, and then power up your Raspberry Pi. The USB audio device should be automatically installed. Go in to the LXDE GUI and open a LXTerminal window and type the following and press Enter:

pi@raspberrypi ~ $ sudo apt-get install alsa-utils_

You may already have this package on your system, but entering this command won't do any harm even if you do. This will install a package of ALSA utilities if you don't already have them (ALSA stands for Advances Linux Sound Architecture). Then type "alsamixer" and press Enter:

pi@raspberrypi ~ $ alsamixer_

This will run the AlsaMixer application in a LXTerminal window:


This shows the on-board audio device's playback control (note that the chip is called "Broadcom Mixer"). Press "F6" and you should see a small pop-up "window" with all the available sound cards listed.


 The item "0 bcm2835 ALSA" is the on-board audio device, and the item "1 C-MediaUSB Audio Device" is the USB audio device. Use the arrow keys to select the "1 C-MediaUSB Audio Device" item and press Enter:


This shows the playback controls for the USB audio device. Use the right and left arrow keys to select the control you wish to adjust and then use the up and down arrow keys to adjust the level. With "Speaker" selected, pressing "m" key on your keyboard will toggle the mute function on the audio output (when muted, "MM" appears instead of "OO" at the bottom of the control). Likewise, the "Mic" control  (which actually refers to the level of microphone input fed back through to the audio output) can be muted, and is shown so in the above screenshot (note the "MM" at the bottom of the control). The "Auto Gain Control" item can not be adjusted with the arrow keys, but can be turned on and off by pressing the "m" key.

Now, if you press "F4" the display will change to show the audio capture control for the USB audio device:


This control is used to adjust the level of audio input from the audio device to the Raspberry Pi, and may be muted by pressing the space bar on your keyboard (but this will not mute the audio fed back through to the audio output).

If you press "F5" you will be able to see and adjust the playback and capture controls together in the same window:


The above screenshot shows the "Speaker" playback control set to 50%, the "Mic" capture control set to 50%, but the "Mic" playback control is muted (and also reduced to zero) and the "Auto Gain Control" is turned on.

The following final section of this post is optional....

There is a "proper" graphical user interface available for the AlsaMixer application. To download and install it type the following at the command line prompt and press Enter:

pi@raspberrypi ~ $ sudo apt-get install alsamixergui_

Once installed, you will find the "Alsamixergui" application under the "Sound & Vision" submenu of the "Start Menu" in the LXDE GUI.


This application works in a similar way to the AlsaMixer application (although note that in the above screenshot the "Mic" controls have been swapped over). In practice I actually found the basic AlsaMixer application (when run in a LXTerminal window) easier to use than the AlsaMixerGUI version, not least of all because the GUI version does not allow you to choose which audio device you want to control - you can only control the "default" ALSA audio device.

To make the USB audio device the default ALSA audio device, you need to create a file called ".asoundrc" in the "/home/pi" folder containing the following text:

pcm.!default {
       type hw
       card 1
       }
ctl.!default {
       type hw
       card 1
       }

If there already is a file called ".asoundrc" in the "/home/pi" folder then append the above text to the end of the existing file. Have a look at this post if you need help creating or editing files.

Once you have saved and closed the ".asoundrc" file you should be able to control the USB audio device using the AlsaMixerGUI application. The above procedure assumes that the on-board audio device is designated "card 0" and that the USB audio device is designated "card 1", but this should be the case as long as you do not have any other audio devices connected to your Raspberry Pi.

104 comments:

  1. This is great! Thanks for sharing!!!

    ReplyDelete
  2. Great introduction.

    I am interested in decoding a quadrature I/Q signal, and hence need stereo input. My first attempt at buying a USB sound card, had only mono input. Does the one you refer to have stereo input?

    Anders

    ReplyDelete
    Replies
    1. Hi Anders,

      I think that even though the audio capture control shows "L" and "R" channels the mic input is mono. However, when I remove the outer casing of the audio device I see that the actual input jack for the mic is stereo (i.e. it has three terminals, the same as the output jack). I also note that the USB audio device uses the CM119 chipset.

      I would be very interested in hearing how you get on - I have also been considering using the Raspberry Pi as part of a Software Defined Radio.

      What SDR software are you running on the Pi?

      Delete
    2. Anyone find a cheap "stereo" audio input device for the Pi?
      I also need to do I/Q input.

      A good wide low noise response would be wonderful. John, KW7A

      Delete
  3. Well, the stereo/mono input of cheap USB sondcards seem to be shrouded in mystery. My Logilink (10EUR) device also have stereo jack, but mono input. Many of the cheaper cards also boast a "stereo input jack", but few of them state whether the mic-input is actually stereo.

    I have just bought the "ASUS Xonar U3", and that has stereo input - both in the brochure and in reality !!! But at 4-times the price, and twice the size.
    .... But now I can proceed.

    I write my own software, I am not decoding ordinary radio, but am playing around with a 24GHz transceiver, using it as Doppler RADAR. The Doppler frequency appear in the audible range, making a sound-card an excellent sampling device, and making simple C programs feasible for signal processing.

    Since I want to make a system with 10 nodes, I am still looking for the cheapest possible USB soundcard with stereo input.

    ReplyDelete
  4. Thanks so much for your great 'how-to'.

    I'm currently trying to invert a small frequency range and than output this signal directly to some active speakers.

    Have you or has anyone here tried that before?
    Could you give me some advice on how to continue?

    Cheers
    obod0002

    ReplyDelete
    Replies
    1. Hi,

      Thanks for your comment, but I'm afraid I can't offer any advice on what you're trying to do... sorry!

      Cheers,

      Tom

      Delete
  5. When I run alsamixer and select the USB codex, when I select f4, I get the error message that the device has no audio input. Any ideas what I am missing. If I run arecord -l, it dose list the USB codec as an input device as Subdevices: 0/1 , so it seems the raspberry pi is seeing the device.

    Larrie, KD7HRJ

    ReplyDelete
  6. Hi Larrie, maybe the USB sound card you're using isn't fully compatible with the Raspberry Pi? I've tried two different USB sound cards, and they both worked, although they used similar chipsets. Anyhow, when running AlsaMixer make sure the card is listed as the USB Audio Device and not the onboard bcm2835.

    ReplyDelete
  7. if everything working fine, is it possible to capture audio input data by Java/Python app? Thanks for reply

    robintptsai@gmail.com

    ReplyDelete
  8. can I connect the dtmf tones to the audio jack

    ReplyDelete
  9. Can this device record input at 8khz?

    ReplyDelete
  10. great . thank you somuch !

    ReplyDelete
  11. Hi, thanks for the post. I have problems with the capture. When I use it for record some audio it comes with a noise and a tone from 600Hz. It could be something wrong by the configuration or the compatibility with raspberry pi B+ or it could be that my sound card is broken?
    Thank you very much.

    ReplyDelete
  12. don't you still need a mic to plug into the sound card if you want to work on speech recognition?

    ReplyDelete
  13. or is it possible to use a usb microphone as well as the sound card to do it?

    ReplyDelete
  14. can i give input through same sd card on which os is installed

    ReplyDelete
  15. can I add multiple USB microphones (up to 4)?

    ReplyDelete
    Replies
    1. Did you ever get an answer on the 4 Mic question? maybe with two stereo usb cards.

      Delete
    2. Did you ever get an answer on the 4 Mic question? maybe with two stereo usb cards.

      Delete
  16. I installed alsamixergui on pi3 with raspbian. too bad it did not work. i was hoping that i could use the utility. i will settle for alsamixer. it actually responds to my keyboard. the gui looks good. it just does not work. no response to mouse or keyboard. nice try, folks.

    ReplyDelete
  17. Hi,

    Will a USB sound adapter like the one that you have mentioned suffice or do I have to plugin a 3.5 mm microphone along with this ? I tried using a usb adapter together with my earphones that have inline microphone in them. They dont seem to work. Can you please guide me ?

    Thanks a lot.

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete
  19. I was doing an online research on How to Write a Personal Experience Essay Effectively before I was directed to this site by the search engine results. I have gathered important information that will help me to compile a comprehensive research paper hence I am very grateful to have landed on this page and I will bookmark it so that I can be visiting it occasionally.

    ReplyDelete
  20. If anyone's interested in backing a Kickstarter audio input project for the pi check this out

    https://www.kickstarter.com/projects/1250664710/804440309?token=b2340424

    ReplyDelete
  21. اسعار تكييفات 2017
    اسعار تكييفات 2018
    عنوان مبيعات يونيو اير
    5شارع عامر امين القومية العربية بجوار الدائري
    12561 إمبابة
    مبيعات يونيو اير
    مبيعات يونيو اير
    مبيعات يونيو اير
    يونيون اير
    صيانة يونيون اير

    تكييف يونيون اير
    تكييف يونيون اير

    خدمة عملاء يونيون ايرجروب

    رقم خدمة عملاء unionaire

    شركة يونيون اير

    تكيفات يونيون ايير
    اسعار تكيفات يونيون ايير
    شاشات يونيون اير

    رقم يونيون اير 19058

    صيانة unionaire

    توكيل يونيون اير

    تكييفات بالتقسيط

    تكييفات يونيون اير



    الخطوط الارضية 0233580534/0233564318/0233564320/0233565322/0233564325/0233509275/023509267/0233509268


    عنوان مبيعات شارب
    4شارع عامر امين القومية العربية بجوار الدائري
    12561 إمبابة

    مبيعات شارب
    شارب
    صيانة شارب

    تكييف شارب
    سعر تكييف شارب

    خدمة عملاء شارب

    رقم خدمة عملاء شارب

    شركة شارب

    تكيفات شارب
    اسعار تكييفات شارب
    شاشات شارب

    رقم شارب 19058

    صيانة شارب

    توكيل شارب

    تكييفات بالتقسيط

    تكييفات شارب

    مبيعات شارب


    الخطوط الارضية 0233580534/0233564318/0233564320/0233565322/0233564325/0233509275/023509267/0233509268

    ReplyDelete
  22. This comment has been removed by the author.

    ReplyDelete
  23. نشتري الاثاث المستعمل بالكويت
    فني صحي بالكويت
    شركة تسليك مجاري بالكويت
    شراء اثاث مستعمل بالكويت
    https://issuu.com/used-furniture-kuwait-1
    نشتري الاثاث المستعمل بالكويت
    فني صحي بالكويت
    شركة تسليك مجاري بالكويت
    شراء اثاث مستعمل بالكويت

    ReplyDelete
  24. نشتري الاثاث المستعمل بالكويت
    شركة نقل عفش بالكويت
    نقل عفش بالكويت رخيص
    فني صحي بالكويت
    تسليك مجاري بالكويت نشتري الاثاث المستعمل بالكويت
    شركة نقل عفش بالكويت
    نقل عفش بالكويت رخيص
    فني صحي بالكويت
    تسليك مجاري بالكويت

    ReplyDelete
  25. فني صحي بالكويت تسليك مجاري بالكويت - معلم صحي بالكويت
    فني صحي بالكويت
    نشتري الاثاث المستعمل بالكويت - شراء الاثاث المستعمل بالكويت
    نشتري الاثاث المستعمل بالكويت
    نقل عفش بالكويت - شركة نقل عفش بالكويت رخيص
    نقل عفش بالكويت

    ReplyDelete

  26. Class College Education training Beauty teaching university academy lesson teacher master student spa manager skin care learn eyelash extensions tattoo spray

    daythammynet
    daythammynet
    daythammynet
    daythammynet
    daythammynet
    daythammynet
    daythammynet
    daythammynet
    daythammynet

    ReplyDelete
  27. We require a review of the rode nt usb VS hyperx quadcast please. Thx hyperx quadcast review

    ReplyDelete
  28. Hmm is anyone else having problems with the images on this blog loading? I'm trying to figure out if its a problem on my end or if it's the blog. Any feedback would be greatly appreciated.

    ReplyDelete
  29. I like looking through an article that will make people think. Also, thank you for allowing me to comment!

    ReplyDelete
  30. Hmm is anyone else experiencing problems with the images on this blog loading? I'm trying to find out if its a problem on my end or if it's the blog. Any suggestions would be greatly appreciated.

    ReplyDelete
  31. Informative blog! it was very useful for me.Thanks for sharing. Do share more ideas regularly.
    Village Talkies a top-quality professional corporate video production company in Bangalore and also best explainer video company in Bangalore & animation video makers in Bangalore, Chennai, India & Maryland, Baltimore, USA provides Corporate & Brand films, Promotional, Marketing videos & Training videos, Product demo videos, Employee videos, Product video explainers, eLearning videos, 2d Animation, 3d Animation, Motion Graphics, Whiteboard Explainer videos Client Testimonial Videos, Video Presentation and more for all start-ups, industries, and corporate companies. From scripting to corporate video production services, explainer & 3d, 2d animation video production , our solutions are customized to your budget, timeline, and to meet the company goals and objectives.
    As a best video production company in Bangalore, we produce quality and creative videos to our clients.

    ReplyDelete
  32. Магазин спортивного питания, официальный сайт которого доступен по адресу: SportsNutrition-24.Com, реализует широкий ассортимент товаров, которые принесут пользу и заслуги как профессиональным спортсменам, так и любителям. Интернет-магазин осуществляет свою деятельность уже многие годы, предоставляя клиентам со всей Рф высококачественное спортивное питание, а помимо этого витамины и специальные препараты - https://sportsnutrition-24.com/aktivnoe-dolgoletie/. Спортпит представляет собой категорию продуктов, которая призвана не только улучшить спортивные заслуги, но и благоприятно влияет на здоровье организма. Подобное питание вводится в ежедневный рацион с целью получения микро- и макроэлементов, витаминов, аминокислот и белков, а также других недостающих веществ. Не секрет, что организм спортсмена в процессе наращивания мышечной массы и адаптации к повышенным нагрузкам, остро нуждается в должном количестве полезных веществ. При всем этом, даже правильное питание и употребление растительной, а кроме этого животной пищи - не гарантирует того, что организм получил нужные аминокислоты либо белки. Чего нельзя сказать о качественном спортивном питании. Об ассортименте товаров Интернет-магазин "SportsNutrition-24.Com" реализует качественную продукцию, которая прошла ряд проверок и получила сертификаты качества. Посетив магазин, заказчики смогут найти для себя товары из следующих категорий: - L-карнитинг (Л-карнитин) представляет собой вещество, родственное витамину B, синтез которого осуществляется в организме; - гейнеры, представляющие из себя, белково-углеводные смеси; - BCAA - средства, содержащие в своем составе три важнейшие аминокислоты, стимулирующие рост мышечной массы; - протеин - чистый белок, употреблять который можно в виде коктейлей; - различные аминокислоты; - а помимо этого ряд других товаров (нитробустеры, жиросжигатели, особые препараты, хондропротекторы, бустеры гормона роста, тестобустеры и многое другое). Об оплате и доставке Интернет-магазин "SportsNutrition-24.Com" предлагает большое обилие товаров, которое в полной мере способно удовлетворить проф и начинающих любителей спорта, включая любителей. Большой опыт позволил компании наладить связь с наикрупнейшими поставщиками и изготовителями питания для спорта, что позволило сделать политику цен гибкой, а цены - демократичными! К примеру, аминокислоты либо гейнер приобрести можно по стоимости, которая на 10-20% ниже, чем у конкурентов. Оплата возможна как наличным, так и безналичным расчетом. Магазин предлагает огромный выбор способов оплаты, включая оплату различными электронными платежными системами, а помимо этого дебетовыми и кредитными картами. Главный офис компании размещен в Санкт-Петербурге, однако доставка товаров осуществляется во все населенные пункты РФ. Помимо самовывоза, получить товар вы можете с помощью любой транспортной компании, подобрать которую каждый клиент может в индивидуальном порядке.

    ReplyDelete
  33. Congratulations on your article, it was very helpful and successful. 21c1603338a8806e9297e7452b9aa3e2
    numara onay
    website kurma
    sms onay

    ReplyDelete
  34. Thank you for your explanation, very good content. 14f865afddf6c67c564a7917b6ce67cd
    define dedektörü

    ReplyDelete
  35. Cool and I have a nifty proposal: Where To Loan For House Renovation house renovation for sale

    ReplyDelete