Part 3 :语音播放器
Part 2 中的录音机录制完成,并把amr
文件的data通过服务器发送给对方,对方收到后无法直接使用这个data进行播放,需要转换成wav
格式data.
- 与part 2相同,也创建两个音频文件到沙盒的Tmp文件夹中
NSString *wavPlayerFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"WAVtemporaryPlayer.wav"];
NSString *amrPlayerFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"AMRtemporaryPlayer.amr"];
- 转换
amr
格式data,成为wav
格式data
- (NSData *)conversionAMRDataToWAVData:(NSData *)amrData
{
NSString *wavPlayerFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"WAVtemporaryPlayer.wav"];
NSString *amrPlayerFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"AMRtemporaryPlayer.amr"];
//amr的data写入文件
[amrData writeToFile:amrPlayerFilePath atomically:YES];
//将AMR文件转码成WAVE文件
amr_file_to_wave_file([amrPlayerFilePath cStringUsingEncoding:NSUTF8StringEncoding],
[wavPlayerFilePath cStringUsingEncoding:NSUTF8StringEncoding]);
//得到转码后wav的data
return [NSData dataWithContentsOfFile:wavPlayerFilePath];
}
- 使用
initWithData:(NSData *)data error:(NSError **)outError
方法初始化播放器
self.audioPlayer = [[AVAudioPlayer alloc]initWithData:[self conversionAMRDataToWAVData:data] error:nil];
self.audioPlayer.meteringEnabled = YES;
self.audioPlayer.delegate = self;
self.audioPlayer.volume = 1.0;
self.audioPlayer.numberOfLoops = 0;
[self.audioPlayer prepareToPlay];
[self.audioPlayer play];
- 播放完成代理方法中做一些事情
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
if (flag) {//播放完成
[self stopPlaying];
if (self.finished) {
self.finished();
}
}
}
- 开启关闭红外传感器,当耳朵贴近屏幕时用听筒播放,当离开是用扬声器播放
//监听红外传感器改变通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proximityStateDidChange) name:UIDeviceProximityStateDidChangeNotification object:nil];
//开始播放时开启红外传感器
[[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
//结束播放时关闭红外传感器
[UIDevice currentDevice].proximityMonitoringEnabled = YES;
- (void)proximityStateDidChange
{
if ([UIDevice currentDevice].proximityState) {
NSLog(@"有物品靠近");
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
} else {
NSLog(@"有物品离开");
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
}
}
Demo 地址 :https://github.com/XL-Andrew/ChatToolBarAudioButton