1.設定音頻參數和相應的回呼函數,當聲音裝置需要資料時SDL會自動調用該回呼函數,填充該結構體。
typedef struct SDL_AudioSpec {int freq;/**< DSP frequency -- samples per second */Uint16 format;/**< Audio data format */Uint8 channels;/**< Number of channels: 1 mono, 2 stereo */Uint8 silence;/**< Audio buffer silence value (calculated) */Uint16 samples;/**< Audio buffer size in samples (power of 2) */Uint16 padding;/**< Necessary for some compile environments */Uint32 size;/**< Audio buffer size in bytes (calculated) *//** * This function is called when the audio device needs more data. * * @param[out] streamA pointer to the audio data buffer * @param[in] lenThe length of the audio buffer in bytes. * * Once the callback returns, the buffer will no longer be valid. * Stereo samples are stored in a LRLRLR ordering. */void (SDLCALL *callback)(void *userdata, Uint8 *stream, int len);void *userdata;} SDL_AudioSpec;
2.開啟聲音裝置
SDL_OpenAudio(&wanted_spec, &spec)
3.開始播放
SDL_PauseAudio(0);
4.在回呼函數中解碼音頻流,將解碼後的buffer複製到stream中
void audio_callback(void *userdata, Uint8 *stream, int len) { //從檔案中讀取資料包,解碼到audio_buf中 ..... memcpy(stream, (uint8_t *)audio_buf + audio_buf_index, len1); .....}