使用sdl播放音频流

获取SDL库:http://download.csdn.net/detail/u011417605/9249383


#include "SDL.h"

static  Uint8  *audio_chunk;
static  Uint32  audio_len;
static  Uint8  *audio_pos;

void  fill_audio(void *udata, Uint8 *stream, int len){
	//SDL 2.0  
	SDL_memset(stream, 0, len);
	if (audio_len == 0)        /*  Only  play  if  we  have  data  left  */
		return;
	len = (len > audio_len ? audio_len : len);   /*  Mix  as  much  data  as  possible  */

	SDL_MixAudio(stream, audio_pos, len, SDL_MIX_MAXVOLUME);
	audio_pos += len;
	audio_len -= len;
}

void Init()
{
    if (SDL_Init(SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
			printf("Could not initialize SDL - %s\n", SDL_GetError());
			return;
		}
		//SDL_AudioSpec  
		SDL_AudioSpec wanted_spec;
		wanted_spec.freq = 44100;
		wanted_spec.format = AUDIO_S16SYS;
		wanted_spec.channels = 2;
		wanted_spec.silence = 0;
		wanted_spec.samples = 1024;
		wanted_spec.callback = fill_audio;

		if (SDL_OpenAudio(&wanted_spec, NULL) < 0){
			printf("can't open audio.\n");
			return;
		}
}

void Play(Uint8 *pStream,int len)
{
   audio_chunk = pStream;
	//Audio buffer length  
	audio_len = len;
	audio_pos = audio_chunk;
	//Play  
	SDL_PauseAudio(0);
	while (audio_len > 0)//Wait until finish  
		SDL_Delay(1);
}


你可能感兴趣的:(sdl,库,播放音频流)