目前,市面上的语音聊天方案很多,但是大多按日活跃收费,算下来很不划算。如果自己做,带宽的压力又大,花费更多。
可以使用oss来做,目前提供这种服务的有阿里云,七牛云,腾讯云等。即将语音在本地app录好后进行压缩,再上传到oss,然后app服务端将存有语音的oss地址发到同一个房间,或者同一个工会的人,然后其他人就根据这个地址到oss去下载语音进行播放。
这个方案既可以android平台,也可以在ios平台使用,唯一不同的是android平台是把wav压缩成mp3,ios是把aac压缩成mp3,但是都是使用lame库进行压缩
以ios/七牛为例,将这些功能封装成了一个sdk,另外,因为没有将全部代码拿出来,所以单纯看下面的代码,里面可能有一些变量没有声明,或者一些函数没有实现等等,但是大部分逻辑都包含了。
初始化:
- (int)initSdk{
if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending)
{
//7.0第一次运行会提示,是否允许使用麦克风
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *sessionError;
//AVAudioSessionCategoryPlayAndRecord用于录音和播放
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
if(session == nil)
NSLog(@"Error creating session: %@", [sessionError description]);
else
[session setActive:YES error:nil];
}
return 0;
}
开始录音
-(void)startRecord:(NSString*)name{
//配置录音参数
NSDictionary* recorderSettingsDict =[[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithInt:AVAudioQualityMin],AVEncoderAudioQualityKey,
[NSNumber numberWithInt:44100],AVSampleRateKey,
[NSNumber numberWithInt:2],AVNumberOfChannelsKey,
[NSNumber numberWithInt:16],AVEncoderBitRateKey,
nil];
if ([self canRecord]) { //用canRecord判断麦克风是否打开等等
NSError *error = nil;
NSString *documentPath =