/***************************************************************************
 *   Copyright (C) 2007 by Andreas Krumnow   *
 *   andreas@krumnow.de   *
 *                                                                         *
 *   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.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "audiothread.h"

audioThread::audioThread(QObject *parent)
 : QThread(parent)
{
    voice = 0;
    tik = new QFile("res/tik.wav");
    tak = new QFile("res/tak.wav");
    spk = new QFile("/dev/dsp");
    audioIn  = new QDataStream(tik);
    audioOut = new QDataStream(spk);
    buf_tik = 0;
    tiksize = 0;
    if (tik->open(QIODevice::ReadOnly)){
        tiksize = tik->size();
        buf_tik = new char[tiksize];
        audioIn->readRawData(buf_tik,tiksize);
        tik->close();
    } // else { error("failed to open: res/tik.wav");}
    buf_tak = 0;
    taksize = 0;
    audioIn->unsetDevice();
    audioIn->setDevice(tak);
    if (tak->open(QIODevice::ReadOnly)){
        taksize = tak->size();
        buf_tak = new char[taksize];
        audioIn->readRawData(buf_tak,taksize);
        tak->close();
    }
    delete audioIn;
    delete tik;
    delete tak;
    if (spk->open(QIODevice::WriteOnly)){
        spk->close();
    }
}

audioThread::~audioThread()
{
    delete spk;
    delete audioOut;
    if (buf_tik != 0) delete buf_tik;
    if (buf_tak != 0) delete buf_tak;
}

void audioThread::run()
{
    spk->open(QIODevice::WriteOnly);
    if (voice != 0){
        audioOut->writeRawData(buf_tik,tiksize);
    } else { 
        audioOut->writeRawData(buf_tak,taksize);
    }
    spk->close();
}

void audioThread::setVoice(int i)
{
    if (i < 1) voice = 0;
    else voice = 1;
}