Error AudioDriverWASAPI::init_capture_device(bool reinit) { Error err = audio_device_init(&audio_input, true, reinit); if (err != OK) return err; // Get the max frames UINT32 max_frames; HRESULT hr = audio_input.audio_client->GetBufferSize(&max_frames); ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN); // Set the buffer size input_buffer.resize(max_frames * CAPTURE_BUFFER_CHANNELS); input_position = 0; input_size = 0; return OK; }
Error AudioDriverWASAPI::init_render_device(bool reinit) { Error err = audio_device_init(&audio_output, false, reinit); if (err != OK) return err; switch (audio_output.channels) { case 2: // Stereo case 4: // Surround 3.1 case 6: // Surround 5.1 case 8: // Surround 7.1 channels = audio_output.channels; break; default: WARN_PRINTS("WASAPI: Unsupported number of channels: " + itos(audio_output.channels)); channels = 2; break; } UINT32 max_frames; HRESULT hr = audio_output.audio_client->GetBufferSize(&max_frames); ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN); // Due to WASAPI Shared Mode we have no control of the buffer size buffer_frames = max_frames; // Sample rate is independent of channels (ref: https://stackoverflow.com/questions/11048825/audio-sample-frequency-rely-on-channels) samples_in.resize(buffer_frames * channels); input_position = 0; input_size = 0; print_verbose("WASAPI: detected " + itos(channels) + " channels"); print_verbose("WASAPI: audio buffer frames: " + itos(buffer_frames) + " calculated latency: " + itos(buffer_frames * 1000 / mix_rate) + "ms"); return OK; }
void wavplay_thread_entry(void *parameter) { FILE *fp = NULL; uint16_t *buffer = NULL; struct wav_info *info = NULL; fp = fopen(file_name, "rb"); if (!fp) { printf("open file failed!\n"); goto __exit; } info = (struct wav_info *) malloc(sizeof(*info)); if (!info) goto __exit; if (fread(&(info->header), sizeof(struct RIFF_HEADER_DEF), 1, fp) != 1) goto __exit; if (fread(&(info->fmt_block), sizeof(struct FMT_BLOCK_DEF), 1, fp) != 1) goto __exit; if (fread(&(info->data_block), sizeof(struct DATA_BLOCK_DEF), 1, fp) != 1) goto __exit; printf("wav information:\n"); printf("samplerate %u\n", info->fmt_block.wav_format.SamplesPerSec); printf("channel %u\n", info->fmt_block.wav_format.Channels); audio_device_init(); audio_device_open(); audio_device_set_rate(info->fmt_block.wav_format.SamplesPerSec); while (!feof(fp)) { int length; buffer = (uint16_t *)audio_device_get_buffer(RT_NULL); length = fread(buffer, 1, BUFSZ, fp); if (length) { if (info->fmt_block.wav_format.Channels == 1) { /* extend to stereo channels */ int index; uint16_t *ptr; ptr = (uint16_t *)((uint8_t *)buffer + BUFSZ * 2); for (index = 1; index < BUFSZ / 2; index ++) { *ptr = *(ptr - 1) = buffer[BUFSZ / 2 - index]; ptr -= 2; } length = length * 2; } audio_device_write((uint8_t *)buffer, length); } else { audio_device_put_buffer((uint8_t *)buffer); break; } } audio_device_close(); __exit: if (fp) fclose(fp); if (info) free(info); }