static void start(sstate *data) { // data->sample = Sound_NewSampleFromFile("rain.mtm", NULL, 65536); data->rw = SDL_RWFromConstMem(song, song_size); data->sample = Sound_NewSample(data->rw, ".mtm", NULL, 65536); if (data->sample == NULL) { fprintf(stderr, "Failed to init sound: %s\n", Sound_GetError()); return; } data->devformat.freq = data->sample->actual.rate; data->devformat.format = data->sample->actual.format; data->devformat.channels = data->sample->actual.channels; data->devformat.samples = 4096; /* I just picked a largish number here. */ data->devformat.callback = audio_callback; data->devformat.userdata = data; if (SDL_OpenAudio(&data->devformat, NULL) < 0) { fprintf(stderr, "Couldn't open audio device: %s.\n", SDL_GetError()); Sound_FreeSample(data->sample); return; } SDL_PauseAudio(0); data->done_flag = 0; }
void SourceSample::Load(char *filename) { #define BUFSIZE 1024 * 1024 SDL_RWops *rwops; rwops = SDL_RWFromFile(filename, "rb"); Sound_Sample *sample = Sound_NewSample(rwops, NULL, _system->GetAudioInfo(), _buffersize ); if(sample == NULL) { fprintf(stderr, "[error] failed loading sample from '%s': %s\n", filename, Sound_GetError()); return; } Sound_DecodeAll(sample); _buffersize = sample->buffer_size; _buffer = new Uint8[_buffersize]; memcpy(_buffer, sample->buffer, _buffersize); Sound_FreeSample(sample); // fprintf(stderr, "done decoding sample '%s'\n", filename); _position = 0; }
void gli_initialize_sound(void) { if (gli_conf_sound == 1) { if (SDL_Init(SDL_INIT_AUDIO) == -1) { gli_strict_warning("SDL init failed\n"); gli_strict_warning(SDL_GetError()); gli_conf_sound = 0; return; } if (Sound_Init() == -1) { gli_strict_warning("SDL Sound init failed\n"); gli_strict_warning(Sound_GetError()); gli_conf_sound = 0; return; } Sound_AudioInfo *audio; audio = malloc(sizeof(Sound_AudioInfo)); audio->format = MIX_DEFAULT_FORMAT; audio->channels = 2; audio->rate = 44100; output = audio; if (Mix_OpenAudio(output->rate, output->format, output->channels, 4096) == -1) { gli_strict_warning("SDL Mixer init failed\n"); gli_strict_warning(Mix_GetError()); gli_conf_sound = 0; return; } int channels = Mix_AllocateChannels(SDL_CHANNELS); Mix_GroupChannels(0, channels - 1 , FREE); } }
SoundBuffer *SoundEmitter::allocateBuffer(const std::string &filename) { SoundBuffer *buffer = bufferHash.value(filename, 0); if (buffer) { /* Buffer still in cashe. * Move to front of priority list */ buffers.remove(buffer->link); buffers.append(buffer->link); return buffer; } else { /* Buffer not in cache, needs to be loaded */ SoundOpenHandler handler; shState->fileSystem().openRead(handler, filename.c_str()); buffer = handler.buffer; if (!buffer) { char buf[512]; snprintf(buf, sizeof(buf), "Unable to decode sound: %s: %s", filename.c_str(), Sound_GetError()); Debug() << buf; return 0; } buffer->key = filename; uint32_t wouldBeBytes = bufferBytes + buffer->bytes; /* If memory limit is reached, delete lowest priority buffer * until there is room or no buffers left */ while (wouldBeBytes > SE_CACHE_MEM && !buffers.isEmpty()) { SoundBuffer *last = buffers.tail(); bufferHash.remove(last->key); buffers.remove(last->link); wouldBeBytes -= last->bytes; SoundBuffer::deref(last); } bufferHash.insert(filename, buffer); buffers.prepend(buffer->link); bufferBytes = wouldBeBytes; return buffer; } }
int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "usage: %s <filename>\n", argv[0]); return 1; } if (SDL_Init(SDL_INIT_AUDIO) != 0) { fprintf(stderr, "Error: %s\n", SDL_GetError()); return 1; } if (Sound_Init() == 0) { fprintf(stderr, "Error: %s\n", Sound_GetError()); return 1; } SDL_RWops* rw = SDL_RWFromFile(argv[1], "r"); if (rw == NULL) { fprintf(stderr, "Error: %s\n", SDL_GetError()); return 1; } Sound_AudioInfo wantedFormat; wantedFormat.channels = 2; wantedFormat.rate = 44100; wantedFormat.format = AUDIO_S16LSB; Sound_Sample* sample = Sound_NewSample(rw, 0, &wantedFormat, 8192); if (sample == 0) { fprintf(stderr, "Error: %s\n", Sound_GetError()); return 1; } Sound_DecodeAll(sample); printf("Format: %s\n", sample->decoder->description); printf("Decoded %d bytes of data.\n", sample->buffer_size); Sound_FreeSample(sample); return 0; }
static void end(sstate *data) { SDL_PauseAudio(1); // SDL_Delay(2 * 1000 * data->devformat.samples / data->devformat.freq); if (data->sample->flags & SOUND_SAMPLEFLAG_ERROR) fprintf(stderr, "Error decoding file: %s\n", Sound_GetError()); Sound_FreeSample(data->sample); SDL_CloseAudio(); }
void *sound_init(void) { static sstate data; if (!Sound_Init()) { fprintf(stderr, "Sound_Init() failed: %s.\n", Sound_GetError()); SDL_Quit(); } memset(&data, 0, sizeof(data)); return &data; }
int main(int argc, char **argv) { int i; if (!Sound_Init()) /* this calls SDL_Init(SDL_INIT_AUDIO) ... */ { fprintf(stderr, "Sound_Init() failed: %s.\n", Sound_GetError()); SDL_Quit(); return(42); } /* if */ for (i = 1; i < argc; i++) /* each arg is an audio file to play. */ playOneSoundFile(argv[i]); /* Shutdown the libraries... */ Sound_Quit(); SDL_Quit(); return(0); } /* main */
SDLSoundSource(SDL_RWops &ops, const char *extension, uint32_t maxBufSize, bool looped) : srcOps(ops), looped(looped) { sample = Sound_NewSample(&srcOps, extension, 0, maxBufSize); if (!sample) { SDL_RWclose(&ops); throw Exception(Exception::SDLError, "SDL_sound: %s", Sound_GetError()); } sampleSize = formatSampleSize(sample->actual.format); alFormat = chooseALFormat(sampleSize, sample->actual.channels); alFreq = sample->actual.rate; }
void SourceMusic::CreateSample(void) { _rwops = SDL_RWFromFile(_filename, "rb"); char *ext = _filename; for(int i = 0; *(_filename + i); i++) { if(*(_filename + i) == '.') ext = _filename + i + 1; } _sample = Sound_NewSample(_rwops, ext, _system->GetAudioInfo(), _sample_buffersize ); if(_sample == NULL) { fprintf(stderr, "[error] failed loading sample type %s, from %s: %s\n", ext, _filename, Sound_GetError()); return; } _read = 0; _decoded = 0; // fprintf(stderr, "created sample\n"); }
int main(int argc, char *argv[]) { SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0"); // SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, "0"); /* initialize SDL first */ if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) { showInitError(std::string("Error initializing SDL: ") + SDL_GetError()); return 0; } if (!EventThread::allocUserEvents()) { showInitError("Error allocating SDL user events"); return 0; } #ifndef WORKDIR_CURRENT /* set working directory */ char *dataDir = SDL_GetBasePath(); if (dataDir) { int result = chdir(dataDir); (void)result; SDL_free(dataDir); } #endif /* now we load the config */ Config conf; conf.read(argc, argv); if (!conf.gameFolder.empty()) if (chdir(conf.gameFolder.c_str()) != 0) { showInitError(std::string("Unable to switch into gameFolder ") + conf.gameFolder); return 0; } conf.readGameINI(); if (conf.windowTitle.empty()) conf.windowTitle = conf.game.title; assert(conf.rgssVersion >= 1 && conf.rgssVersion <= 3); printRgssVersion(conf.rgssVersion); int imgFlags = IMG_INIT_PNG | IMG_INIT_JPG; if (IMG_Init(imgFlags) != imgFlags) { showInitError(std::string("Error initializing SDL_image: ") + SDL_GetError()); SDL_Quit(); return 0; } if (TTF_Init() < 0) { showInitError(std::string("Error initializing SDL_ttf: ") + SDL_GetError()); IMG_Quit(); SDL_Quit(); return 0; } if (Sound_Init() == 0) { showInitError(std::string("Error initializing SDL_sound: ") + Sound_GetError()); TTF_Quit(); IMG_Quit(); SDL_Quit(); return 0; } SDL_Window *win; Uint32 winFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_INPUT_FOCUS; if (conf.winResizable) winFlags |= SDL_WINDOW_RESIZABLE; if (conf.fullscreen) winFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP; win = SDL_CreateWindow(conf.windowTitle.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, conf.defScreenW, conf.defScreenH, winFlags); if (!win) { showInitError(std::string("Error creating window: ") + SDL_GetError()); return 0; } /* OSX and Windows have their own native ways of * dealing with icons; don't interfere with them */ #ifdef __LINUX__ setupWindowIcon(conf, win); #else (void) setupWindowIcon; #endif ALCdevice *alcDev = alcOpenDevice(0); if (!alcDev) { showInitError("Error opening OpenAL device"); SDL_DestroyWindow(win); TTF_Quit(); IMG_Quit(); SDL_Quit(); return 0; } SDL_DisplayMode mode; SDL_GetDisplayMode(0, 0, &mode); /* Can't sync to display refresh rate if its value is unknown */ if (!mode.refresh_rate) conf.syncToRefreshrate = false; EventThread eventThread; RGSSThreadData rtData(&eventThread, argv[0], win, alcDev, mode.refresh_rate, conf); int winW, winH; SDL_GetWindowSize(win, &winW, &winH); rtData.windowSizeMsg.post(Vec2i(winW, winH)); /* Load and post key bindings */ rtData.bindingUpdateMsg.post(loadBindings(conf)); /* Start RGSS thread */ SDL_Thread *rgssThread = SDL_CreateThread(rgssThreadFun, "rgss", &rtData); /* Start event processing */ eventThread.process(rtData); /* Request RGSS thread to stop */ rtData.rqTerm.set(); /* Wait for RGSS thread response */ for (int i = 0; i < 1000; ++i) { /* We can stop waiting when the request was ack'd */ if (rtData.rqTermAck) { Debug() << "RGSS thread ack'd request after" << i*10 << "ms"; break; } /* Give RGSS thread some time to respond */ SDL_Delay(10); } /* If RGSS thread ack'd request, wait for it to shutdown, * otherwise abandon hope and just end the process as is. */ if (rtData.rqTermAck) SDL_WaitThread(rgssThread, 0); else SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, conf.windowTitle.c_str(), "The RGSS script seems to be stuck and mkxp will now force quit", win); if (!rtData.rgssErrorMsg.empty()) { Debug() << rtData.rgssErrorMsg; SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, conf.windowTitle.c_str(), rtData.rgssErrorMsg.c_str(), win); } /* Clean up any remainin events */ eventThread.cleanup(); Debug() << "Shutting down."; alcCloseDevice(alcDev); SDL_DestroyWindow(win); Sound_Quit(); TTF_Quit(); IMG_Quit(); SDL_Quit(); return 0; }
int openAudio_platform(AudioInstance* instance) { char path[512]; char fullPath[512]; getcwd(path, sizeof(path)); snprintf(fullPath, sizeof(fullPath)-1, "%s\\data\\%s", path, instance->mClip->mPath); char* slash = strchr(fullPath, '/'); while(slash) { *slash = '\\'; slash = strchr(slash+1, '/'); } instance->mAudio.mSample = Sound_NewSampleFromFile(fullPath, NULL, SDL_BUFFER_SIZE); if(instance->mAudio.mSample == NULL) { dprintf("%s", Sound_GetError()); return -1; } dprintf("Opened as:\n channels: %d\n format: 0x%x\n rate: %d", instance->mAudio.mSample->actual.channels, instance->mAudio.mSample->actual.format, instance->mAudio.mSample->actual.rate ); int bytes; switch(instance->mAudio.mSample->actual.channels) { case 1: if((instance->mAudio.mSample->actual.format & 0x0008) == 0x0008) { instance->mFormat = AL_FORMAT_MONO8; bytes = 1; } else { instance->mFormat = AL_FORMAT_MONO16; bytes = 2; } break; case 2: if((instance->mAudio.mSample->actual.format & 0x0008) == 0x0008) { instance->mFormat = AL_FORMAT_STEREO8; bytes = 1; } else { instance->mFormat = AL_FORMAT_STEREO16; bytes = 2; } break; default: dprintf("WTF"); } instance->mSampleRate = instance->mAudio.mSample->actual.rate; instance->mAudio.mReadFreq = ((float)SDL_BUFFER_SIZE/(float)(instance->mSampleRate * bytes)) * 1000000.0f; instance->mAudio.mReadFreq -= 500000; instance->mAudio.mNextRead = getTime(); return 0; }
int main(int argc, char *argv[]) { /* initialize SDL first */ if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) { Debug() << "Error initializing SDL:" << SDL_GetError(); return 0; } if (!EventThread::allocUserEvents()) { Debug() << "Error allocating SDL user events"; return 0; } #ifndef WORKDIR_CURRENT /* set working directory */ char *dataDir = SDL_GetBasePath(); if (dataDir) { int result = chdir(dataDir); (void)result; SDL_free(dataDir); } #endif /* now we load the config */ Config conf; conf.read(argc, argv); conf.readGameINI(); assert(conf.rgssVersion >= 1 && conf.rgssVersion <= 3); printRgssVersion(conf.rgssVersion); int imgFlags = IMG_INIT_PNG | IMG_INIT_JPG; if (IMG_Init(imgFlags) != imgFlags) { Debug() << "Error initializing SDL_image:" << SDL_GetError(); SDL_Quit(); return 0; } if (TTF_Init() < 0) { Debug() << "Error initializing SDL_ttf:" << SDL_GetError(); IMG_Quit(); SDL_Quit(); return 0; } if (Sound_Init() == 0) { Debug() << "Error initializing SDL_sound:" << Sound_GetError(); TTF_Quit(); IMG_Quit(); SDL_Quit(); return 0; } SDL_SetHint("SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS", "0"); SDL_Window *win; Uint32 winFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_INPUT_FOCUS; if (conf.winResizable) winFlags |= SDL_WINDOW_RESIZABLE; if (conf.fullscreen) winFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP; win = SDL_CreateWindow(conf.game.title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, conf.defScreenW, conf.defScreenH, winFlags); if (!win) { Debug() << "Error creating window:" << SDL_GetError(); return 0; } if (!conf.iconPath.empty()) { SDL_Surface *iconImg = IMG_Load(conf.iconPath.c_str()); if (iconImg) { SDL_SetWindowIcon(win, iconImg); SDL_FreeSurface(iconImg); } } EventThread eventThread; RGSSThreadData rtData(&eventThread, argv[0], win, conf); /* Load and post key bindings */ rtData.bindingUpdateMsg.post(loadBindings(conf)); /* Start RGSS thread */ SDL_Thread *rgssThread = SDL_CreateThread(rgssThreadFun, "rgss", &rtData); /* Start event processing */ eventThread.process(rtData); /* Request RGSS thread to stop */ rtData.rqTerm.set(); /* Wait for RGSS thread response */ for (int i = 0; i < 1000; ++i) { /* We can stop waiting when the request was ack'd */ if (rtData.rqTermAck) { Debug() << "RGSS thread ack'd request after" << i*10 << "ms"; break; } /* Give RGSS thread some time to respond */ SDL_Delay(10); } /* If RGSS thread ack'd request, wait for it to shutdown, * otherwise abandon hope and just end the process as is. */ if (rtData.rqTermAck) SDL_WaitThread(rgssThread, 0); else SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, conf.game.title.c_str(), "The RGSS script seems to be stuck and mkxp will now force quit", win); if (!rtData.rgssErrorMsg.empty()) { Debug() << rtData.rgssErrorMsg; SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, conf.game.title.c_str(), rtData.rgssErrorMsg.c_str(), win); } /* Clean up any remainin events */ eventThread.cleanup(); /* Store key bindings */ BDescVec keyBinds; rtData.bindingUpdateMsg.get(keyBinds); storeBindings(keyBinds, rtData.config); Debug() << "Shutting down."; SDL_DestroyWindow(win); Sound_Quit(); TTF_Quit(); IMG_Quit(); SDL_Quit(); return 0; }
int main (int argc, char **argv) { Sound_AudioInfo info; Sound_Sample *stream; SDL_AudioSpec spec; /* Handle command line options. */ if (options (argc, argv) < 0) { puts ("Usage: amaranth OPTIONS FILE\n\n"); puts ("Options\n"); puts (" -r RATE sampling rate bits/second (default: 441000)\n"); puts (" -f FMT sample format (default: signed 16-bit little-endian)\n"); puts (" -c COUNT number of channels (default: 2)\n"); puts (" -s SIZE audio buffer size in samples (default: 4096)\n"); puts ("\nFormats accepted by -f option:\n"); puts (" S16LSB signed 16-bit little-endian\n"); return 1; } /* Initialize SDL audio subsystem. */ if (SDL_Init (SDL_INIT_AUDIO) < 0) { fprintf (stderr, "amaranth: cannot initialize SDL audio: %s\n", SDL_GetError ()); return 1; } /* Initialize SDL_sound library. */ if (Sound_Init () < 0) { fprintf (stderr, "amaranth: cannot initialize SDL_sound: %s\n", Sound_GetError ()); return 1; } /* Open the sound stream. */ info.format = sample_format; info.channels = channel_count; info.rate = sample_rate; stream = Sound_NewSampleFromFile (filename, &info, 4096); if (stream == NULL) { fprintf (stderr, "amaranth: cannot open sound stream %s: %s\n", filename, Sound_GetError ()); return 1; } /* Open the audio device. */ spec.freq = sample_rate; spec.format = sample_format; spec.channels = channel_count; spec.samples = samples; spec.callback = stream_callback; spec.userdata = (void *) stream; if (SDL_OpenAudio (&spec, NULL) < 0) { fprintf (stderr, "amaranth: cannot open audio device: %s\n", SDL_GetError ()); return 1; } /* Start playing audio and engage infinite loop. */ SDL_PauseAudio (0); for (;;) SDL_Delay (10000); /* NOT REACHED */ return 0; }
static void playOneSoundFile(const char *fname) { PlaysoundAudioCallbackData data; memset(&data, '\0', sizeof (PlaysoundAudioCallbackData)); data.sample = Sound_NewSampleFromFile(fname, NULL, 65536); if (data.sample == NULL) { fprintf(stderr, "Couldn't load '%s': %s.\n", fname, Sound_GetError()); return; } /* if */ /* * Open device in format of the the sound to be played. * We open and close the device for each sound file, so that SDL * handles the data conversion to hardware format; this is the * easy way out, but isn't practical for most apps. Usually you'll * want to pick one format for all the data or one format for the * audio device and convert the data when needed. This is a more * complex issue than I can describe in a source code comment, though. */ data.devformat.freq = data.sample->actual.rate; data.devformat.format = data.sample->actual.format; data.devformat.channels = data.sample->actual.channels; data.devformat.samples = 4096; /* I just picked a largish number here. */ data.devformat.callback = audio_callback; data.devformat.userdata = &data; if (SDL_OpenAudio(&data.devformat, NULL) < 0) { fprintf(stderr, "Couldn't open audio device: %s.\n", SDL_GetError()); Sound_FreeSample(data.sample); return; } /* if */ printf("Now playing [%s]...\n", fname); SDL_PauseAudio(0); /* SDL audio device is "paused" right after opening. */ global_done_flag = 0; /* the audio callback will flip this flag. */ while (!global_done_flag) SDL_Delay(10); /* just wait for the audio callback to finish. */ /* at this point, we've played the entire audio file. */ SDL_PauseAudio(1); /* so stop the device. */ /* * Sleep two buffers' worth of audio before closing, in order * to allow the playback to finish. This isn't always enough; * perhaps SDL needs a way to explicitly wait for device drain? * Most apps don't have this issue, since they aren't explicitly * closing the device as soon as a sound file is done playback. * As an alternative for this app, you could also change the callback * to write silence for a call or two before flipping global_done_flag. */ SDL_Delay(2 * 1000 * data.devformat.samples / data.devformat.freq); /* if there was an error, tell the user. */ if (data.sample->flags & SOUND_SAMPLEFLAG_ERROR) fprintf(stderr, "Error decoding file: %s\n", Sound_GetError()); Sound_FreeSample(data.sample); /* clean up SDL_Sound resources... */ SDL_CloseAudio(); /* will reopen with next file's format. */ } /* playOneSoundFile */