www.gusucode.com > 基于RTP语音压缩解压缩的发送与接收代码 > 基于RTP语音压缩解压缩的发送与接收代码/sender/sender.cpp

    /*
   Here's a small IPv4 example: it asks for a portbase and a destination and 
   starts sending packets to that destination.
*/

#include "sender.h"

//
// This function checks if there was a RTP error. If so, it displays an error
// message and exists.
//

void checkerror(int rtperr)
{
	if (rtperr < 0)
	{
		std::cout << "ERROR: " << RTPGetErrorString(rtperr) << std::endl;
		exit(-1);
	}
}

//
// The main routine
//

int main(void)
{
#ifdef WIN32
	WSADATA dat;
	WSAStartup(MAKEWORD(2,2),&dat);
	printf("WSAStartup\n");
#endif // WIN32
	
	RTPSession sess;
	u_int32_t destip;
	int status, i;
	RTPUDPv4TransmissionParams transparams;
	RTPSessionParams sessparams;
	FILE *fp = NULL;
	unsigned char speechBuffer[4096];
	unsigned int bufferSize;
	unsigned int AllSize;

	// 获得接收端的IP地址和端口号
	destip = inet_addr(DEST_IP);
	if (destip == INADDR_NONE)
	{
		printf("Bad IP address specified\n");
		return -1;
	}
	destip = ntohl(destip);

	// 创建RTP会话
	sessparams.SetOwnTimestampUnit(1.0/10.0);		
	sessparams.SetAcceptOwnPackets(false);
	transparams.SetPortbase(PORT_BASE);			//local port
	status = sess.Create(sessparams, &transparams);	
	checkerror(status);
	
	// 指定RTP数据接收端
	RTPIPv4Address addr(destip, DEST_PORT);		//dsp2 port
	status = sess.AddDestination(addr);
	checkerror(status);

	// 设置RTP会话默认参数
	sess.SetDefaultPayloadType(0);
	sess.SetDefaultMark(false);
	sess.SetDefaultTimestampIncrement(10);

	if (fp != NULL)
		fclose(fp);
	if ((fp = fopen(VOX_FILE, "rb")) == NULL)
	{
		printf("Failed to open vox file '%s'\n", VOX_FILE);
		return -1;
	}
	AllSize = 0;
	while ( ! feof(fp) )
	{
		// read from vox file 
		//if (bufferSize = fread(speechBuffer, sizeof(char), 160, fp)) < 160)
		//	break;
		bufferSize = fread(speechBuffer, sizeof(char), 160, fp);
		
		printf("bufferSize=%d\n", bufferSize);
		AllSize += bufferSize;
		// send the packet
		status = sess.SendPacket(speechBuffer, bufferSize);
		checkerror(status);
		
#ifndef RTP_SUPPORT_THREAD
		status = sess.Poll();
		checkerror(status);
#endif // RTP_SUPPORT_THREAD
		
		//RTPTime::Wait(RTPTime(0,20));
		RTPTime::Wait(0.015);
		//Sleep(100);
	}
	printf("AllSize=%d\n", AllSize);

	sess.BYEDestroy(RTPTime(10,0),0,0);

#ifdef WIN32
	WSACleanup();
	printf("WSACleanup\n");
#endif // WIN32
	return 0;
}