Ejemplo n.º 1
0
void* recAndSend(void * param){
  ALshort alrecBuffer[SAMPLESIZE];
  ALint alSample;
  ALCdevice* device = alcOpenDevice(NULL);
  ALCcontext* context = alcCreateContext(device,  NULL);
  alcMakeContextCurrent(context);
  ALCdevice* alDevice = alcCaptureOpenDevice(NULL, SRATE, AL_FORMAT_MONO16, SAMPLESIZE);
  alcGetError(alDevice);
  alcCaptureStart(alDevice);
  alcGetError(alDevice);
  while (1){
    alcGetIntegerv(alDevice, ALC_CAPTURE_SAMPLES, (ALCsizei)sizeof(ALint), &alSample);
    alcGetError(alDevice);
    if(alSample > SAMPLESIZE/2) {
      alcCaptureSamples(alDevice, (ALCvoid *)alrecBuffer, alSample);
      int n;
      socklen_t addrlen = sizeof(senderinfo);
      int i;
      for(i=0; i<alSample; i++){
        if(abs((int)alrecBuffer[i]) > (0.8*INT16_MAX) ) break;
      }
      if(i==alSample) continue;
      if((n = sendto(sock, alrecBuffer, alSample*2, 0, (struct sockaddr *)&senderinfo, addrlen)) != alSample*2){
        perror("sendto");
        exit(1);
      }
    }
    if(callFlag==OFF) break;
  }
  alcCaptureCloseDevice(alDevice);
  alcCaptureStop(alDevice);
  alcCloseDevice(device);
//  fprintf(stderr, "close recAndSend\n");
}
void OpenALController::record() {
	ALubyte *captureBufPtr;
	qDebug() << "Starting capture NOW!";
	m_samplesCaptured = 0;
	captureBufPtr = m_captureBuffer;

	this->setRecording(true);
	alcCaptureStart(m_captureDev);
	alcGetIntegerv(m_captureDev, ALC_CAPTURE_SAMPLES,
			(ALCsizei) sizeof(ALubyte), &m_samplesAvailable);
	while (m_samplesCaptured < FREQ * 5) {
		if (0 < m_samplesAvailable && m_samplesAvailable <= FREQ) {
			alcCaptureSamples(m_captureDev, captureBufPtr, m_samplesAvailable);
			checkError("alcCaptureSamples");
			m_samplesCaptured += m_samplesAvailable;
			//qDebug()
			//		<<qPrintable(QString("Captured %1 samples (adding %2)\n").arg(m_samplesCaptured).arg(m_samplesAvailable));

			// Advance the buffer (two bytes per sample * number of samples)
			captureBufPtr += m_samplesAvailable * 2;
		} else {
			qDebug() << "No captured samples:" << m_samplesAvailable;
		}
		// Wait for a bit
		//alutSleep(0.02);
		printf(".");
		fflush(stdout);
		alcGetIntegerv(m_captureDev, ALC_CAPTURE_SAMPLES,
				(ALCsizei) sizeof(ALubyte), &m_samplesAvailable);
	}
	qDebug() << "\nDone capturing.\n";
	alcCaptureStop(m_captureDev);
	this->setRecording(false);
}
Ejemplo n.º 3
0
 int psm_record::stop(){
     if(context_->device){
         alcCaptureStop(context_->device);
         alcCaptureCloseDevice(context_->device);
         context_->device = NULL;
     }
     return 0;
 }
Ejemplo n.º 4
0
static void alccapturestop(void *handle) {
    if(handle == (void*)1) {
        audio_close(handle);
        return;
    }

    alcCaptureStop(handle);
}
Ejemplo n.º 5
0
void RecordingDevice::stop()
{
	if (!isRecording())
		return;

	alcCaptureStop(device);
	alcCaptureCloseDevice(device);
	device = nullptr;
}
Ejemplo n.º 6
0
CaptureStreamT::~CaptureStreamT()
{
    if (m_IsCapturing)
    {
        alcCaptureStop(m_CaptureDevice);
        m_IsCapturing=false;
    }

    alcCaptureCloseDevice(m_CaptureDevice);
}
Ejemplo n.º 7
0
	love::sound::SoundData * Audio::stopRecording(bool returnData)
	{
		if (!canRecord()) return NULL;
		love::sound::SoundData * sd = NULL;
		if (returnData) {
			sd = getRecordedData();
		}
		alcCaptureStop(capture);
		return sd;
	}
Ejemplo n.º 8
0
void Core::cleanupCall(int callId)
{
    qDebug() << QString("Core: cleaning up call %1").arg(callId);
    calls[callId].active = false;
    disconnect(calls[callId].sendAudioTimer,0,0,0);
    calls[callId].sendAudioTimer->stop();
    calls[callId].sendVideoTimer->stop();
    if (calls[callId].videoEnabled)
        Widget::getInstance()->getCamera()->unsuscribe();
    alcCaptureStop(alInDev);
}
Ejemplo n.º 9
0
void SoundRecorder::cleanup()
{
    // Stop the capture
    alcCaptureStop(captureDevice);

    // Get the samples left in the buffer
    processCapturedSamples();

    // Close the device
    alcCaptureCloseDevice(captureDevice);
    captureDevice = NULL;
}
Ejemplo n.º 10
0
AudioAnalyzer::~AudioAnalyzer(void)
{
	if (!initialized)
		return;
	
    alcCaptureStop(inputDevice);
    alcCaptureCloseDevice(inputDevice);
    delete[] capturedBuffer;
    delete[] ffted;
	delete[] ar;
	delete[] ai;
}
Ejemplo n.º 11
0
/**
 * @brief Close active audio input device.
 */
void OpenAL::cleanupInput()
{
    if (!alInDev)
        return;

    qDebug() << "Closing audio input";
    alcCaptureStop(alInDev);
    if (alcCaptureCloseDevice(alInDev) == ALC_TRUE)
        alInDev = nullptr;
    else
        qWarning() << "Failed to close input";
}
Ejemplo n.º 12
0
	void cAudioCapture::stopCapture()
	{
		cAudioMutexBasicLock lock(Mutex);
		if(CaptureDevice && Ready)
		{
			alcCaptureStop(CaptureDevice);
			updateCaptureBuffer(true);
			checkError();
			getLogger()->logDebug("AudioCapture", "OpenAL Capture Stopped.");
			signalEvent(ON_ENDCAPTURE);
		}
		Capturing = false;
	}
Ejemplo n.º 13
0
void SoundController::setIsRecording(bool isit)
{
	if (isRecording == isit) return;
	
	isRecording = isit;
	
	if (!captureDevice) return;
	
	if (isRecording)
		alcCaptureStart(captureDevice);
	else
		alcCaptureStop(captureDevice);
}
Ejemplo n.º 14
0
static gboolean
gst_openal_src_unprepare (GstAudioSrc * asrc)
{

  GstOpenalSrc *osrc = GST_OPENAL_SRC (asrc);

  GST_INFO_OBJECT (osrc, "Close device : %s", osrc->deviceName);
  if (osrc->deviceHandle) {
    alcCaptureStop (osrc->deviceHandle);
    alcCaptureCloseDevice (osrc->deviceHandle);
  }

  return TRUE;
}
Ejemplo n.º 15
0
static gboolean
gst_openal_src_unprepare (GstAudioSrc * audiosrc)
{
  GstOpenalSrc *openalsrc = GST_OPENAL_SRC (audiosrc);

  if (openalsrc->device) {
    alcCaptureStop (openalsrc->device);

    if (alcCaptureCloseDevice (openalsrc->device) == ALC_FALSE) {
      GST_ELEMENT_ERROR (openalsrc, RESOURCE, CLOSE,
          ("Could not close device."), GST_ALC_ERROR (openalsrc->device));
      return FALSE;
    }
  }

  return TRUE;
}
Ejemplo n.º 16
0
Archivo: audio.cpp Proyecto: czaks/qTox
/**
Open an input device, use before suscribing
*/
void Audio::openInput(const QString& inDevDescr)
{
    QMutexLocker lock(&audioInLock);

    if (alInDev) {
#if (!FIX_SND_PCM_PREPARE_BUG)
        qDebug() << "stopping capture";
        alcCaptureStop(alInDev);
#endif
        alcCaptureCloseDevice(alInDev);
    }
    alInDev = nullptr;

    /// TODO: Try to actually detect if our audio source is stereo
    int stereoFlag = AUDIO_CHANNELS == 1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
    const uint32_t sampleRate = AUDIO_SAMPLE_RATE;
    const uint16_t frameDuration = AUDIO_FRAME_DURATION;
    const uint32_t chnls = AUDIO_CHANNELS;
    const ALCsizei bufSize = (frameDuration * sampleRate * 4) / 1000 * chnls;
    if (inDevDescr.isEmpty())
        alInDev = alcCaptureOpenDevice(nullptr, sampleRate, stereoFlag, bufSize);
    else
        alInDev = alcCaptureOpenDevice(inDevDescr.toStdString().c_str(),
                                       sampleRate, stereoFlag, bufSize);

    if (alInDev)
        qDebug() << "Opening audio input "<<inDevDescr;
    else
        qWarning() << "Cannot open input audio device " + inDevDescr;

    Core* core = Core::getInstance();
    if (core)
        core->getAv()->resetCallSources(); // Force to regen each group call's sources

    // Restart the capture if necessary
    if (alInDev)
    {
        alcCaptureStart(alInDev);
    }
    else
    {
#if (FIX_SND_PCM_PREPARE_BUG)
        alcCaptureStart(alInDev);
#endif
    }
}
Ejemplo n.º 17
0
/**
Open an input device, use before suscribing
*/
void Audio::openInput(const QString& inDevDescr)
{
    QMutexLocker lock(&audioInLock);

    if (alInDev) {
#if (!FIX_SND_PCM_PREPARE_BUG)
        qDebug() << "stopping capture";
        alcCaptureStop(alInDev);
#endif
        alcCaptureCloseDevice(alInDev);
    }
    alInDev = nullptr;

    int stereoFlag = av_DefaultSettings.audio_channels==1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
    const uint32_t sampleRate = av_DefaultSettings.audio_sample_rate;
    const uint16_t frameDuration = av_DefaultSettings.audio_frame_duration;
    const uint32_t chnls = av_DefaultSettings.audio_channels;
    const ALCsizei bufSize = (frameDuration * sampleRate * 4) / 1000 * chnls;
    if (inDevDescr.isEmpty())
        alInDev = alcCaptureOpenDevice(nullptr, sampleRate, stereoFlag, bufSize);
    else
        alInDev = alcCaptureOpenDevice(inDevDescr.toStdString().c_str(),
                                       sampleRate, stereoFlag, bufSize);

    if (alInDev)
        qDebug() << "Opening audio input "<<inDevDescr;
    else
        qWarning() << "Cannot open input audio device " + inDevDescr;

    Core* core = Core::getInstance();
    if (core)
        core->resetCallSources(); // Force to regen each group call's sources

    // Restart the capture if necessary
    if (alInDev)
    {
        alcCaptureStart(alInDev);
    }
    else
    {
#if (FIX_SND_PCM_PREPARE_BUG)
        alcCaptureStart(alInDev);
#endif
    }
}
Ejemplo n.º 18
0
void Audio::unsuscribeInput()
{
    if (!alInDev)
    {
        qWarning()<<"input device is closed";
        return;
    }

    qDebug() << "unsuscribing input";
    QMutexLocker lock(audioInLock);
    if (!--userCount && alInDev)
    {
#if (!FIX_SND_PCM_PREPARE_BUG)
        qDebug() << "stopping capture";
        alcCaptureStop(alInDev);
#endif
    }
}
Ejemplo n.º 19
0
const QString& AudioRecorder::stopRecord()
{
    m_updateRecordTimer.stop();

    alcCaptureStop(m_recordDevice);
    alcCaptureCloseDevice(m_recordDevice);

    uint8_t* data = (uint8_t*)m_sampleArray.data();
    size_t size = m_sampleArray.size();
    if (size > 0)
        writeFrame((uint8_t*)m_sampleArray.data(), size);

    m_sampleArray.clear();

    cleanupRecorder();

    return m_filePath;
}
Ejemplo n.º 20
0
bool CaptureStreamT::Rewind()
{
    // Captured input cannot be rewound...
    if (m_IsCapturing)
    {
        alcCaptureStop(m_CaptureDevice);
        m_IsCapturing=false;

        // Remove all remaining capture samples from the capture device, so that when capturing is restarted,
        // no stale samples are left. According to the OpenAL spec, this should happen automatically:
        // "The amount of audio samples available after restarting a stopped capture device is reset to zero.",
        // but not all implementations seem to conform.
        ReduceSamplesTo(0);
    }

    m_ZeroSamples=0;
    return true;
}
void SdSoundCaptureAL::StopCapture()
{
	// Stop the FFT
	done_fft();
    
	// Stop capture
	alcCaptureStop(pCaptureDevice);
    
	// Fill in Size information in Wave Header
	if( audioFile )
	{
		fseek( audioFile, 4, SEEK_SET);
		BtU32 iSize = iDataSize + sizeof(WAVEHEADER) - 8;
		fwrite( &iSize, 4, 1, audioFile );
		fseek( audioFile, 42, SEEK_SET );
		fwrite( &iDataSize, 4, 1, audioFile );
        
		// Close the audio file
		fclose( audioFile );
	}
}
Ejemplo n.º 22
0
void plVoiceRecorder::SetMikeOpen(hsBool b)
{
    ALCdevice *device = plgAudioSys::GetCaptureDevice();
    if (fRecording && device)
    {       
        if (b)
        {
            alcCaptureStart(device);
        }
        else
        {
            alcCaptureStop(device);
        }
        DrawTalkIcon(b);
        fMikeOpen = b;
    }
    else
    {
        DrawDisabledIcon(b);        // voice recording is unavailable or disabled
    }
}
Ejemplo n.º 23
0
Archivo: audio.cpp Proyecto: czaks/qTox
/**
Close an input device, please don't use unless everyone's unsuscribed
*/
void Audio::closeInput()
{
    qDebug() << "Closing input";
    QMutexLocker locker(&audioInLock);
    if (alInDev)
    {
#if (!FIX_SND_PCM_PREPARE_BUG)
        qDebug() << "stopping capture";
        alcCaptureStop(alInDev);
#endif

        if (alcCaptureCloseDevice(alInDev) == ALC_TRUE)
        {
            alInDev = nullptr;
            inputSubscriptions = 0;
        }
        else
        {
            qWarning() << "Failed to close input";
        }
    }
}
Ejemplo n.º 24
0
ALCvoid CDECL wine_alcCaptureStop(ALCdevice *device)
{
    alcCaptureStop(device);
}
Ejemplo n.º 25
0
void Audio::unsuscribeInput()
{
    if (!--userCount && alInDev)
        alcCaptureStop(alInDev);
}
Ejemplo n.º 26
0
void Cyanide::audio_thread()
{
    return;
    const char *device_list, *output_device = NULL;
    //void *audio_device = NULL;

    bool call[MAX_CALLS] = {0}, preview = 0;
    bool audio_filtering_enabled;
    // bool groups_audio[MAX_NUM_GROUPS] = {0};

    int perframe = (av_DefaultSettings.audio_frame_duration * av_DefaultSettings.audio_sample_rate) / 1000;
    uint8_t buf[perframe * 2 * av_DefaultSettings.audio_channels], dest[perframe * 2 * av_DefaultSettings.audio_channels];
    memset(buf, 0, sizeof(buf));

    uint8_t audio_count = 0;
    bool record_on = 0;
    #ifdef AUDIO_FILTERING
    qDebug() << "Audio Filtering enabled";
    #ifdef ALC_LOOPBACK_CAPTURE_SAMPLES
    qDebug() << "Echo cancellation enabled";
    #endif
    #endif

    qDebug() << "frame size:" << perframe;

    device_list = alcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
    if(device_list) {
        output_device = device_list;
        qDebug() << "Output Device List:";
        while(*device_list) {
            qDebug() << device_list;
            //postmessage(NEW_AUDIO_OUT_DEVICE, 0, 0, (void*)device_list);
            device_list += strlen(device_list) + 1;
        }
    }

    device_out = alcOpenDevice(output_device);
    if(!device_out) {
        qDebug() << "alcOpenDevice() failed";
        return;
    }

    int attrlist[] = {  ALC_FREQUENCY, av_DefaultSettings.audio_sample_rate,
                        ALC_INVALID };

    context = alcCreateContext(device_out, attrlist);
    if(!alcMakeContextCurrent(context)) {
        qDebug() << "alcMakeContextCurrent() failed";
        alcCloseDevice(device_out);
        return;
    }

    alGenSources(countof(source), source);

    static ALuint ringSrc[MAX_CALLS];
    alGenSources(MAX_CALLS, ringSrc);

    /* Create buffer to store samples */
    ALuint RingBuffer;
    alGenBuffers(1, &RingBuffer);

    {
        float frequency1 = 441.f;
        float frequency2 = 882.f;
        int seconds = 4;
        unsigned sample_rate = 22050;
        size_t buf_size = seconds * sample_rate * 2; //16 bit (2 bytes per sample)
        int16_t *samples = (int16_t*)malloc(buf_size * sizeof(int16_t));
        if (!samples)
            return;

        /*Generate an electronic ringer sound that quickly alternates between two frequencies*/
        int index = 0;
        for(index = 0; index < buf_size; ++index) {
            if ((index / (sample_rate)) % 4 < 2 ) {//4 second ring cycle, first 2 secondsring, the rest(2 seconds) is silence
                if((index / 1000) % 2 == 1) {
                    samples[index] = 5000 * sin((2.0 * 3.1415926 * frequency1) / sample_rate * index); //5000=amplitude(volume level). It can be from zero to 32700
                } else {
                    samples[index] = 5000 * sin((2.0 * 3.1415926 * frequency2) / sample_rate * index);
                }
            } else {
                samples[index] = 0;
            }
        }

        alBufferData(RingBuffer, AL_FORMAT_MONO16, samples, buf_size, sample_rate);
        free(samples);
    }

    {
        unsigned int i;
        for (i = 0; i < MAX_CALLS; ++i) {
            alSourcei(ringSrc[i], AL_LOOPING, AL_TRUE);
            alSourcei(ringSrc[i], AL_BUFFER, RingBuffer);
        }
    }
    #ifdef AUDIO_FILTERING
    Filter_Audio *f_a = NULL;
    #endif

    while(loop == LOOP_RUN || loop == LOOP_SUSPEND) {
        #ifdef AUDIO_FILTERING
        if (!f_a && audio_filtering_enabled) {
            f_a = new_filter_audio(av_DefaultSettings.audio_sample_rate);
            if (!f_a) {
                audio_filtering_enabled = 0;
                qDebug() << "filter audio failed";
            } else {
                qDebug() << "filter audio on";
            }
        } else if (f_a && !audio_filtering_enabled) {
            kill_filter_audio(f_a);
            f_a = NULL;
            qDebug() << "filter audio off";
        }
        #else
        if (audio_filtering_enabled)
            audio_filtering_enabled = 0;
        #endif

        bool sleep = 1;

        if(record_on) {
            ALint samples;
            alcGetIntegerv(device_in, ALC_CAPTURE_SAMPLES, sizeof(samples), &samples);
            if(samples >= perframe) {
                alcCaptureSamples(device_in, buf, perframe);
                if (samples >= perframe * 2) {
                    sleep = 0;
                }
            }
        }

        #ifdef AUDIO_FILTERING
        #ifdef ALC_LOOPBACK_CAPTURE_SAMPLES
        if (f_a && audio_filtering_enabled) {
            ALint samples;
            alcGetIntegerv(device_out, ALC_LOOPBACK_CAPTURE_SAMPLES, sizeof(samples), &samples);
            if(samples >= perframe) {
                int16_t buffer[perframe];
                alcCaptureSamplesLoopback(device_out, buffer, perframe);
                pass_audio_output(f_a, buffer, perframe);
                set_echo_delay_ms(f_a, 5);
                    if (samples >= perframe * 2) {
                    sleep = 0;
                }
            }
        }
        #endif
        #endif

        #ifdef AUDIO_FILTERING
        if (f_a && filter_audio(f_a, (int16_t*)buf, perframe) == -1) {
            qDebug() << "filter audio error";
        }
        #endif
        if(preview) {
            audio_play(0, (int16_t*)buf, perframe, av_DefaultSettings.audio_channels, av_DefaultSettings.audio_sample_rate);
        }

        int i;
        for(i = 0; i < MAX_CALLS; i++) {
            if(call[i]) {
                int r;
                if((r = toxav_prepare_audio_frame(toxav, i, dest, sizeof(dest), (const int16_t*)buf, perframe)) < 0) {
                    qDebug() << "toxav_prepare_audio_frame error" << r;
                    continue;
                }

                if((r = toxav_send_audio(toxav, i, dest, r)) < 0) {
                    qDebug() << "toxav_send_audio error" << r;
                }
            }
        }

        if (sleep) {
            usleep(5000);
        }
    }

    #ifdef AUDIO_FILTERING
    kill_filter_audio(f_a);
    #endif

    //missing some cleanup ?
    alDeleteSources(MAX_CALLS, ringSrc);
    alDeleteSources(countof(source), source);
    alDeleteBuffers(1, &RingBuffer);

    if(device_in) {
        if(record_on) {
            alcCaptureStop(device_in);
        }
        alcCaptureCloseDevice(device_in);
    }

    alcMakeContextCurrent(NULL);
    alcDestroyContext(context);
    alcCloseDevice(device_out);
}
Ejemplo n.º 27
0
int main(void) 
{ 
/*Отсюда нужно две функции - 
1) получение в виде массива (строки) данных с микрофона за время необработки
2)Проигрвание строки равной значению

*/
const ALCchar *   devices; 
const ALCchar *         ptr; 
ALCdevice *       mainDev; 
ALCcontext *      mainContext; 
ALCdevice *       captureDev; 
ALubyte           captureBuffer[1048576]; 
ALubyte           *captureBufPtr; 
ALint             samplesAvailable; 
ALint             samplesCaptured; 
time_t            currentTime; 
time_t            lastTime; 
ALuint            buffer; 
ALuint            source; 
ALint             playState; 
int               i; 

// Print the list of capture devices 
printf("Available playback devices:\n");

devices = alcGetString(NULL, ALC_DEVICE_SPECIFIER); 
ptr = devices; 
//while (ptr[0] != NULL)
while (*ptr)
{ 
   printf("   %s\n", ptr); 
   ptr += strlen(ptr) + 1; 
} 

// Open a playback device and create a context first 
printf("Opening playback device:\n"); 
mainDev = alcOpenDevice(NULL); 
if (mainDev == NULL) 
{ 
  printf("Unable to open playback device!\n"); 
  exit(1); 
} 
devices = alcGetString(mainDev, ALC_DEVICE_SPECIFIER); 
printf("   opened device '%s'\n", devices); 
mainContext = alcCreateContext(mainDev, NULL); 
if (mainContext == NULL) 
{ 
  printf("Unable to create playback context!\n"); 
  exit(1); 
} 
printf("   created playback context\n"); 

// Make the playback context current 
alcMakeContextCurrent(mainContext); 
alcProcessContext(mainContext); 

// Print the list of capture devices 

printf("Available capture devices:\n"); 
devices = alcGetString(NULL, ALC_CAPTURE_DEVICE_SPECIFIER); 
ptr = devices; 

//while (ptr[0] != NULL)
while (*ptr)
{ 
   printf("   %s\n", ptr); 
   ptr += strlen(ptr) + 1; 
}

// Open the default device 
printf("Opening capture device:\n"); 
captureDev = alcCaptureOpenDevice(NULL, 8000, AL_FORMAT_MONO16, 800); 
if (captureDev == NULL) 
{  
  printf("   Unable to open device!\n"); 
  exit(1); 
} 
devices = alcGetString(captureDev, ALC_CAPTURE_DEVICE_SPECIFIER); 
printf("   opened device %s\n", devices); 

// Wait for three seconds to prompt the user 
for (i = 3; i > 0; i--) 
{ 
  printf("Starting capture in %d...\r", i); 
  fflush(stdout); 
  lastTime = time(NULL); 
  currentTime = lastTime; 
  while (currentTime == lastTime) 
  { 
     currentTime = time(NULL); 
     usleep(100000); 
  } 
} 

printf("Starting capture NOW!\n"); 
fflush(stdout); 
lastTime = currentTime; 

// Capture (roughly) five seconds of audio 
alcCaptureStart(captureDev); 
samplesCaptured = 0; 
captureBufPtr = captureBuffer; 
while (currentTime < (lastTime + 5)) 
{ 
  // Get the number of samples available 
  alcGetIntegerv(captureDev, ALC_CAPTURE_SAMPLES, 1, &samplesAvailable); 

  // Copy the samples to our capture buffer 
  if (samplesAvailable > 0) 
  { 
     alcCaptureSamples(captureDev, captureBufPtr, samplesAvailable); 
     samplesCaptured += samplesAvailable; 
     printf("Captured %d samples (adding %d)\r", samplesCaptured, 
        samplesAvailable); 
     fflush(stdout); 

     // Advance the buffer (two bytes per sample * number of samples) 
     captureBufPtr += samplesAvailable * 2; 
  } 

  // Wait for a bit 
  usleep(10000); 

  // Update the clock 
  currentTime = time(NULL); 
} 
printf("\nPausing capture.\n"); 
alcCaptureStop(captureDev); 

// Wait for three seconds to prompt the user 
for (i = 3; i > 0; i--) 
{ 
  printf("Resuming capture in %d...\r", i); 
  fflush(stdout); 
  lastTime = time(NULL); 
  currentTime = lastTime; 
  while (currentTime == lastTime) 
  { 
     currentTime = time(NULL); 
     usleep(100000); 
  } 
} 

printf("Resuming capture NOW!\n"); 
fflush(stdout); 
lastTime = currentTime; 

// Capture (roughly) five seconds of audio 
alcCaptureStart(captureDev); 
while (currentTime < (lastTime + 5)) 
{ 
  // Get the number of samples available 
  alcGetIntegerv(captureDev, ALC_CAPTURE_SAMPLES, 1, &samplesAvailable); 

  // Copy the samples to our capture buffer 
  if (samplesAvailable > 0) 
  { 
     alcCaptureSamples(captureDev, captureBufPtr, samplesAvailable); 
     samplesCaptured += samplesAvailable; 
     printf("Captured %d samples (adding %d)\r", samplesCaptured, 
        samplesAvailable); 
     fflush(stdout); 

     // Advance the buffer (two bytes per sample * number of samples) 
     captureBufPtr += samplesAvailable * 2; 
  } 

  // Wait for a bit 
  usleep(10000); 

  // Update the clock 
  currentTime = time(NULL); 
} 

printf("\nDone capturing.\n"); 
alcCaptureStop(captureDev); 

// Play back the captured data 
printf("Starting playback...\n"); 
fflush(stdout); 

// Generate an OpenAL buffer for the captured data 
alGenBuffers(1, &buffer); 
alGenSources(1, &source); 
alBufferData(buffer, AL_FORMAT_MONO16, captureBuffer,samplesCaptured*2, 8000); 
alSourcei(source, AL_BUFFER, buffer); 
alSourcePlay(source); 

// Wait for the source to stop playing 
playState = AL_PLAYING; 
while (playState == AL_PLAYING) 
{ 
  printf("  source %d is playing...\r", source); 
  fflush(stdout); 
  alGetSourcei(source, AL_SOURCE_STATE, &playState); 
  usleep(100000); 
} 
printf("\nDone with playback.\n"); 
fflush(stdout); 

// Shut down OpenAL 
alDeleteSources(1, &source); 
alDeleteBuffers(1, &buffer); 
alcMakeContextCurrent(NULL); 
alcCloseDevice(mainDev); 
alcCaptureCloseDevice(captureDev); 
}
Ejemplo n.º 28
0
	void CaptureThread::stopCapture()
	{
		qDebug() << "[CaptureThread::stopCapture()]";
		if( _pCaptureDevice && _capturing )
		{
			//
			// Stop capture
			//
			_capturing = false;
			_captureMutex.lock();
			alcCaptureStop( _pCaptureDevice );

			//
			// Check if any Samples haven't been consumed yet
			//
			alcGetIntegerv( _pCaptureDevice, ALC_CAPTURE_SAMPLES, 1, &_iSamplesAvailable) ;
#if defined( __WIN32__ ) || defined( _WIN32 )
			int sampleSize = BUFFERSIZE / _sWaveHeader.wfex.nBlockAlign;
#else
                        int sampleSize = BUFFERSIZE / _nBlockAlign;
#endif
			while( _iSamplesAvailable )
			{
#if defined( __WIN32__ ) || defined( _WIN32 )
				if( _iSamplesAvailable > ( sampleSize ) )
				{
					alcCaptureSamples( _pCaptureDevice, _buffer, sampleSize );
					//
					//	Write to file
					//
					writeAudioBufferToFile( BUFFERSIZE );
					//fwrite( outputBuffer, BUFFERSIZE, 1, _pFile );
					//fwrite( _buffer, BUFFERSIZE, 1, _pFile );
					_iSamplesAvailable -= sampleSize;
					_iDataSize += BUFFERSIZE;
				}
				else
				{
					qDebug() << "[CaptureThread::stopCapture()]"<< " ----------- last sample size: " << _iSamplesAvailable;
					alcCaptureSamples(_pCaptureDevice, _buffer, _iSamplesAvailable);
					//
					//	Write to file
					//
					int writeSize = _iSamplesAvailable * _sWaveHeader.wfex.nBlockAlign;
					writeAudioBufferToFile( writeSize );
					//fwrite(_buffer, _iSamplesAvailable * _sWaveHeader.wfex.nBlockAlign, 1, _pFile);
					_iDataSize += writeSize;
					_iSamplesAvailable = 0;
				}
#else
				if( _iSamplesAvailable > sampleSize )
				{
					alcCaptureSamples( _pCaptureDevice, _buffer, sampleSize );					
					sf_write_short( _pFile, (short *)_buffer, BUFFERSIZE );
					_iSamplesAvailable -= sampleSize;
					_iDataSize += BUFFERSIZE;
				}
				else
				{
					sf_write_short( _pFile, (short *)_buffer, BUFFERSIZE);
					_iDataSize += _iSamplesAvailable * _nBlockAlign;
					_iSamplesAvailable = 0;
				}
#endif
			}

			_captureMutex.unlock();

#if defined( __WIN32__ ) || defined( _WIN32 )
			// Fill in Size information in Wave Header
			fseek( _pFile, 4, SEEK_SET );
			_iSize = _iDataSize + sizeof(WAVEHEADER) - 8;
			fwrite(&_iSize, 4, 1, _pFile);
			fseek(_pFile, 42, SEEK_SET);
			fwrite(&_iDataSize, 4, 1, _pFile);

			fclose( _pFile );
#else
			sf_close( _pFile ) ;
			terminate();
#endif
			emit signalCaptureEnded();
			emit captureVolume( 0 );
		}
	}
Ejemplo n.º 29
0
 ~SoundManager() {
     alcCaptureStop(in_device);
     alcCaptureCloseDevice(in_device);
 }
ALCaptureWorker::~ALCaptureWorker() 
{
	alcCaptureStop(device);
}