sdl-audio/example-test-code/temp.cpp
2024-10-10 20:11:57 +08:00

86 lines
1.9 KiB
C++

#include <SDL2/SDL.h>
#include <SDL2/SDL_audio.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
using namespace std;
SDL_AudioSpec want, have;
SDL_AudioDeviceID player;
void SDLCALL callback_player( void* userdata, Uint8* stream, int len)
{
for (int i = 0; i < len; i ++) {
auto value = Uint8(sin(i) * 1000);
stream[i] = value ;
}
}
auto setupAudioPlayer()
{
printf("### Device Player ###\n");
int num = SDL_GetNumAudioDevices(false);
printf("num: %d\n", num);
for (int i = 0; i < num; i++) {
auto name = SDL_GetAudioDeviceName(i, false);
printf("%d: %s\n", i, name);
}
int deviceIndex;
printf("select device to player audio: ");
scanf("%d", &deviceIndex);
printf("\n");
SDL_memset(&want, 0, sizeof(want)); /* or SDL_zero(want) */
want.freq = 44100;
want.format = AUDIO_F32;
want.channels = 2;
want.samples = 1024;
want.callback = callback_player; // you wrote this function elsewhere.
//want.size = 512;
SDL_AudioDeviceID player = SDL_OpenAudioDevice(SDL_GetAudioDeviceName(deviceIndex, false), SDL_FALSE, &want, &have, SDL_AUDIO_ALLOW_FORMAT_CHANGE);
if (player == 0) {
printf("Failed to open player device! SDL Error: %s", SDL_GetError());
} else {
printf("freq %d \nformat %d \nchannels %d \nsamples %d\n", have.freq, have.format, have.channels, have.samples);
}
return player;
}
void destroyAudio()
{
SDL_CloseAudioDevice(player);
SDL_Quit();
}
int main(int n, char** args)
{
int err = SDL_Init(SDL_INIT_AUDIO);
printf("error: %d", err);
if (err < 0) {
printf("erorr: %d\n", err);
printf("Failed to init audio! SDL Error: %s", SDL_GetError());
}
//recorder = setupAudioRecorder();
auto player = setupAudioPlayer();
printf("player: %d\n", player);
//loadWave();
printf("playing\n");
//SDL_PauseAudioDevice(recorder, 0);
SDL_PauseAudioDevice(player, 0);
//SDL_SemWait(sem);
SDL_Delay(10000);
destroyAudio();
//system("pause");
return 0;
}