iOS 声音播放
1、声明播放对象
@property (nonatomic, strong) AVAudioPlayer *player;
2、//创建AVAudioPlayer对象
-(AVAudioPlayer *)player{
if (_player == nil) {
NSError *error = nil;
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.url error:&error];
_player.volume = 1.0;
_player.delegate = self;
if (error) {
NSLog(@”player error:%@”,error);
}
}
NSLog(@”play”);
return _player;
}
3、//点击播放录音
– (IBAction)playRcd:(id)sender {
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback; //外放
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;//话筒
AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,sizeof (audioRouteOverride),&audioRouteOverride);
[self.player play];
}
4、//AVAudioPlayer的代理方法,不销毁不能二次播放
– (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
NSLog(@”%s”,__func__);
self.player = nil;
}