#include <stdio.h>
#include <unistd.h>
#include <linux/soundcard.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
    int mixer = -1;
    int volume = 0;
    int oldVolume = 0;

    if ((mixer = open("/dev/mixer", O_RDWR|O_NONBLOCK)) == -1)
    {
        printf("Can't open\n");
        exit(1);
    }
    while (1)
    {    
        if ( ioctl(mixer, SOUND_MIXER_READ_VOLUME, &volume) == -1)
        {
            printf("Unable to read volume\n");
            exit(1);
        }
        if (volume != oldVolume)
        {
            if (ioctl(mixer, MIXER_WRITE(SOUND_MIXER_PHONEOUT), &volume) == -1)
            {
                printf("Unable to set the volume\n");
                exit(1);
            }
            printf("Changed volume from %i to %i\n", oldVolume, volume);
            fflush(NULL);
            oldVolume = volume;
        }
        usleep(500000);
    }
    close(mixer);
    return 0;
}
