You are not logged in.

#1 2009-10-28 02:14:28

MattSmith
Member
From: Wellington, New Zealand
Registered: 2009-02-08
Posts: 108

USB audio

I recently broke my audio jack by tripping over my head phones, lol. Anyway I picked up a Diamond Sound Tube... it's a neat little usb sound card that works well with linux and dramatically improved my sound quality! I was wondering if there's a better way to back and forth between sound cards then having to use-> asoundconf set-default-card <PARAMETER> 

I don't mind doing it that way too much but it would be nice if it could just switch when I plugged the thing it. Thanks for you time! big_smile


A thing of beauty is a joy forever
                         
                               -John Keats

Offline

#2 2009-10-28 07:01:34

seiichiro0185
Member
From: Leipzig/Germany
Registered: 2009-04-09
Posts: 226
Website

Re: USB audio

I have a solution like that on my laptop, unfortunalety I can't give you the exact details since my laptop is broken ATM. But the general procedure I use is to use an udev rule to generate a /etc/asound.conf that makes the USB-Soundcard the default one when its plugged in and remove the config when it is unplugged. Hopefully my laptop will get repaired this week so I can post further details.


My System: Dell XPS 13 | i7-7560U | 16GB RAM | 512GB SSD | FHD Screen | Arch Linux
My Workstation/Server: Supermicro X11SSZ-F | Xeon E3-1245 v6 | 64GB RAM | 1TB SSD Raid 1 + 6TB HDD ZFS Raid Z1 | Proxmox VE
My Stuff at Github: github
My Homepage: Seiichiros HP

Offline

#3 2009-10-28 07:33:03

scragar
Member
Registered: 2009-07-14
Posts: 108

Re: USB audio

In the time until a better solution is posted back when I used ubuntu there was a python script called asoundconf-gtk which was small and simple to allow you to change the default sound card.

I'm not sure if it's any good to you, but this is the source:

#!/usr/bin/env python
# asoundconf-gtk - GTK GUI to select the default sound card
#
# (C) 2006 Toby Smithe
# asoundconf parts (C) 2005 Canonical Ltd.
# gourmet parts (C) 2005 Thomas Hinkle (and any other gourmet developers)
# Both the asoundconf and gourmet projects are also licenced under the 
# GPLv2 or any later version in exactly the same way as this project.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import sys, re, os, pygtk, gtk, string

######################################
#START small block of asoundconf code#
######################################

def getcards():
    cardspath = '/proc/asound/cards'
    if not os.path.exists(cardspath):
        return False
    procfile = open(cardspath, 'rb')
    cardline = re.compile('^\s*\d+\s*\[')
    card_lines = []
    lines = procfile.readlines()
    for l in lines:
        if cardline.match(l):
            card_lines.append(re.sub(r'^\s*\d+\s*\[(\w+)\s*\].+','\\1',l))
    return card_lines # Snipped here

####################################
#END small block of asoundconf code#
####################################

###################################
#START small block of gourmet code#
###################################

def cb_set_active_text (combobox, text, col=0):
    """Set the active text of combobox to text. We fail
    if the text is not already in the model. Column is the column
    of the model from which text is drawn."""
    model = combobox.get_model()
    n = 0
    for rw in model:
        if rw[col]==text:
            combobox.set_active(n)
            return n
           n += 1
    return None

#################################
#END small block of gourmet code#
#################################

asoundconf = "/usr/bin/asoundconf"

def die_on_error():
    '''Kill the application if it cannot run'''
    if not os.path.exists("/proc/asound/cards"):
        print "You need at least one ALSA sound card for this to work!"
        sys.exit(-1)
    if os.system(asoundconf + " is-active"):
        print "You need to make sure asoundconf is active!"
        print "By default, asoundconf's configuration file is ~/.asoundrc.asoundconf"
        print "and must be included in ~/.asoundrc. Open this file to make sure it is!"
        sys.exit(-2)

def get(setting):
    '''Get an asoundconf setting'''
    cmd = asoundconf + " get " + setting
    output = os.popen(cmd).readlines()
    return output

def get_default_card():
    '''# Get the default PCM card (but assume this is the default card for everything)
    This is just a very simple wrapper for get(...) as otherwise I'd have to repeat
    a load (well, two lines) of code.'''
    value_raw = get("defaults.pcm.card")
    if not value_raw:
        return 0
    value = string.strip(value_raw[0])
    return value

def set_default_card(card):
    '''Set the default card using asoundconf'''
    call = asoundconf + " set-default-card " + card
    return os.system(call)

def set_pulseaudio():
    call = asoundconf + " set-pulseaudio"
    return os.system(call)

def unset_pulseaudio():
    call = asoundconf + " unset-pulseaudio"
    return os.system(call)
    
class asoundconf_gtk:
    def destroy(self, widget, data=None):
        '''This is a stub function to allow for stuff to be done on close'''
        gtk.main_quit()

    def delete_event(self, widget, event, data=None):
        '''Again, a stub to allow stuff to happen when widgets are deleted'''
        return False

    def choose(self, widget, data=None):
        '''Function to set thde default card on choice'''
        card = widget.get_active_text()
        if card == "PulseAudio":
            set_pulseaudio()
        else:
            unset_pulseaudio()
            set_default_card(card)

    def pulse(self, widget, data=None):
        '''Enables/Disables PulseAudio support'''
        active = widget.get_active()
        if active:
            value = set_pulseaudio()
        else:
            value = unset_pulseaudio()
        return value

    def reset(self, widget, data=None):
        '''Reset the default card to the current default'''
        if self.combo.get_active_text() == "PulseAudio":
            set_pulseaudio()
        else:
            unset_pulseaudio()            
            set_default_card(get_default_card())
    
    def __init__(self):
        # Initiate the window
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_title("Default Sound Card")
        # Create an HBox box
        self.selectionbox = gtk.HBox(False, 0)
        # Create a button
        self.button = gtk.Button("Quit")
        self.button.connect("clicked", self.reset, None)
        self.button.connect_object("clicked", gtk.Widget.destroy, self.window)
        # Create combobox
        self.combo = gtk.combo_box_new_text()
        self.liststore = self.combo.get_model()
        # Add cards to combobox liststore
        cards = getcards()
        if not cards:
            return False
        for card in cards:
            self.combo.append_text(card.strip())
        self.combo.connect("changed", self.choose, None)
        # Create a label
        self.label = gtk.Label("Select default card: ")
        # Add contents to HBox "selectionbox"
        self.selectionbox.pack_start(self.combo, True, True, 0)        
        self.selectionbox.pack_start(self.button, True, True, 0)
        # Create a VBox
        self.vbox = gtk.VBox(False, 0)
        self.window.add(self.vbox)
        self.vbox.pack_start(self.label, True, True, 0)
        self.vbox.pack_start(self.selectionbox, True, True, 0)
        # Create PulseAudio checkbox if ALSA PulseAudio plugin installed
        if os.path.exists("/usr/lib/alsa-lib/libasound_module_pcm_pulse.so") and os.path.exists("/usr/lib/alsa-lib/libasound_module_ctl_pulse.so"):
            #self.pulsecheck = gtk.CheckButton("Use _PulseAudio?")
            self.combo.append_text("PulseAudio")
            try: pcmDefault = get("pcm.!default")[0]
            except: pcmDefault = ""
            if pcmDefault == "{ type pulse }\n":
                #self.pulsecheck.set_active(True)
                cb_set_active_text(self.combo, "PulseAudio")
            else:
                # Select current default 
                cb_set_active_text(self.combo, get_default_card())
            #self.pulsecheck.connect("toggled", self.pulse, None)
            #self.vbox.pack_start(self.pulsecheck, True, True, 0)
        # Connect up window events
        self.window.connect("destroy",self.destroy)
        self.window.connect("delete_event",self.delete_event)
        # Show window and contents
        self.window.show_all()

    def main(self):
        '''Do the stuffs'''
        gtk.main()

if __name__ == "__main__":
    die_on_error()
    aconf = asoundconf_gtk()
    sys.exit(aconf.main())

Offline

#4 2009-10-28 08:26:31

MattSmith
Member
From: Wellington, New Zealand
Registered: 2009-02-08
Posts: 108

Re: USB audio

Thanks for the replies! Scragar, thanks for posting the script, but asoundconf does that same thing without using gtk I think. I'm talking for something along the lines of what seiichiro0185 is dicribing.

@ seiichiro0185 - Is this done using script that you wrote?

On a kinda off topic side note, do you guys no a good place (website) to learn shell script or would you suggest learning python for what seiichiro0185 is talking about? -- as you can tell I'm a pretty big n00b when it comes to talk about script vs programming language

sorry about the off topic, and I appreciate the help!


A thing of beauty is a joy forever
                         
                               -John Keats

Offline

#5 2009-10-28 08:38:19

scragar
Member
Registered: 2009-07-14
Posts: 108

Re: USB audio

MattSmith wrote:

Thanks for the replies! Scragar, thanks for posting the script, but asoundconf does that same thing without using gtk I think. I'm talking for something along the lines of what seiichiro0185 is dicribing.

@ seiichiro0185 - Is this done using script that you wrote?

On a kinda off topic side note, do you guys no a good place (website) to learn shell script or would you suggest learning python for what seiichiro0185 is talking about? -- as you can tell I'm a pretty big n00b when it comes to talk about script vs programming language

sorry about the off topic, and I appreciate the help!

I posted the script in case you knew some sort of programming language and the contents of it were any help, judging by your second question though I see that's not the case.

Bash scripting is actually rather simple, it's just a series of commands to be executed one after another possibly including functions, variables etc like Bash already supports. The man pages are probably the best guides for most things, once you understand a few basic things like the if

if [ condition ]; then
  stuff to do
fi

I'm not a very good person to ask for tutorials though.

Python is a very good language for a first language, it enforces the use of whitespace which is something you absolutely must learn if you are to be a good programmer(without it you'll wind up writing code that no-one wants to read and you can't maintain/update).

Offline

#6 2009-10-28 09:01:07

seiichiro0185
Member
From: Leipzig/Germany
Registered: 2009-04-09
Posts: 226
Website

Re: USB audio

MattSmith wrote:

@ seiichiro0185 - Is this done using script that you wrote?

yes, its a little script I wrote and an udev rule

MattSmith wrote:

On a kinda off topic side note, do you guys no a good place (website) to learn shell script or would you suggest learning python for what seiichiro0185 is talking about? -- as you can tell I'm a pretty big n00b when it comes to talk about script vs programming language

For stuff like this I think bash script is pretty ideal since bash is on almost any system, is fast and small (smaller than python or other full fledged scripting languages anyways) and does all that is needed and more.

I learned most of my bash knowledge from here: http://tldp.org/LDP/abs/html/


My System: Dell XPS 13 | i7-7560U | 16GB RAM | 512GB SSD | FHD Screen | Arch Linux
My Workstation/Server: Supermicro X11SSZ-F | Xeon E3-1245 v6 | 64GB RAM | 1TB SSD Raid 1 + 6TB HDD ZFS Raid Z1 | Proxmox VE
My Stuff at Github: github
My Homepage: Seiichiros HP

Offline

#7 2009-10-28 09:08:29

ngoonee
Forum Fellow
From: Between Thailand and Singapore
Registered: 2009-03-17
Posts: 7,355

Re: USB audio

I'll just throw in the suggestion to use Pulseaudio, one of its main advantage is on-the-fly moving of streams between different outputs.


Allan-Volunteer on the (topic being discussed) mailn lists. You never get the people who matters attention on the forums.
jasonwryan-Installing Arch is a measure of your literacy. Maintaining Arch is a measure of your diligence. Contributing to Arch is a measure of your competence.
Griemak-Bleeding edge, not bleeding flat. Edge denotes falls will occur from time to time. Bring your own parachute.

Offline

#8 2009-10-28 13:25:43

MattSmith
Member
From: Wellington, New Zealand
Registered: 2009-02-08
Posts: 108

Re: USB audio

@seiichiro0185: Thanks for the link, it's now added to my bookmarks and I will start working my way through it. If you can't get your script that switches the default sound card I think it will be a fun first project for me to try and get my own script to do it properly!

@ scragar: thanks for trying, I am pretty useless with anything outside of C like syntax and it has to be basic c like syntax at that tongue

@ngoonee: I have herd some pretty rough stuff about pulse, mostly it being unnecessary (if not slightly buggy) and more suited to servers for networked audio. However if it offers on-the-fly switching of streams it could be useful. I have a few requirements of it. I know very little of pulse, but from what I understand, it sounds like pulse will sit on top of alsa and serve as a handler for audio. Meaning that I can still use MOC and alsamixer to adjust sound levels and play music, however a script would still be necessary to switch the card when plugged it, but I wont have to restart any applications it will just be seamless. Is this anywhere close to correct?


A thing of beauty is a joy forever
                         
                               -John Keats

Offline

#9 2009-10-29 00:46:33

ngoonee
Forum Fellow
From: Between Thailand and Singapore
Registered: 2009-03-17
Posts: 7,355

Re: USB audio

MattSmith wrote:

@ngoonee: I have herd some pretty rough stuff about pulse, mostly it being unnecessary (if not slightly buggy) and more suited to servers for networked audio. However if it offers on-the-fly switching of streams it could be useful. I have a few requirements of it. I know very little of pulse, but from what I understand, it sounds like pulse will sit on top of alsa and serve as a handler for audio. Meaning that I can still use MOC and alsamixer to adjust sound levels and play music, however a script would still be necessary to switch the card when plugged it, but I wont have to restart any applications it will just be seamless. Is this anywhere close to correct?

Pulse has had bad press, from 2 sources, firstly the poor dumb users who were hit by distros like Ubuntu in their initial pulse offering (implementation was horrible, I got hit by this one), secondly by purist linux people who don't see the point of a sound-server and say "hey, alsa can do everything you want!".

Pulseaudio is a sound server, meaning alsa handles the device and pulse handles the audio. All your apps play through pulse, either directly (most apps are capable of this) or indirectly through an alsa plugin. I use mpd, and the alsa->pulse plugin works, though I prefer compiling mpd with direct pulse support myself.

Switching cards and stuff is mainly done through the pavucontrol app, graphically clicking on a stream and sending it to the appropriate sink. There's 'memory' logic where a stream reappears on the same sink it was last on, if available, or falls back to some other sink (sinks being sound output from the computer).

Concerning not having to restart any app, this is true as long as the pulseaudio server doesn't die. Hasn't happened to me in a while, except when I used to be doing stupid things with jack and its pulse module smile. You can even unplug your USB soundcard and unload the drivers for your internal sound card and pulse's server shouldn't die (it just creates a null output and waits for a real soundcard to come along).


Allan-Volunteer on the (topic being discussed) mailn lists. You never get the people who matters attention on the forums.
jasonwryan-Installing Arch is a measure of your literacy. Maintaining Arch is a measure of your diligence. Contributing to Arch is a measure of your competence.
Griemak-Bleeding edge, not bleeding flat. Edge denotes falls will occur from time to time. Bring your own parachute.

Offline

#10 2009-11-01 03:16:03

MattSmith
Member
From: Wellington, New Zealand
Registered: 2009-02-08
Posts: 108

Re: USB audio

Sorry about the long response, but I have decided to use pulse. Been looking into it a bit and I only see advantages in my case... so why not? Thanks everyone that responded for your help!


A thing of beauty is a joy forever
                         
                               -John Keats

Offline

Board footer

Powered by FluxBB