当前位置: 代码迷 >> Iphone >> 在 iPhone 静音情况下,播发 MP3 文件的代码
  详细解决方案

在 iPhone 静音情况下,播发 MP3 文件的代码

热度:461   发布时间:2016-04-25 06:35:39.0
在 iPhone 静音情况下,播放 MP3 文件的代码

在 iPhone 静音情况下,播放 MP3 文件的代码

?

在 iPhone 静音的情况下,iOS 系统自带的 iPod 应用可以正常播放音乐,但很多开发者的第三方应用中却不行,下面这段代码能保证您的应用在 iPhone 静音情况下,照常播放 MP3 文件。

- (IBAction) record:(id)sender
{
????
????NSError *error = nil;
????BOOL b = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:&error];
????[[AVAudioSession sharedInstance] setDelegate:self];
????if(b){
????????NSLog(@"set audio session category record victory%d",b);
????}else {
????????NSLog(@"error=================%@",error);
????}
????b = [[AVAudioSession sharedInstance] setActive:YES error:&error];
????if(b){
????????NSLog(@"set active yes %d",b);
????}else {
????????NSLog(@"error=================%@",error);
????}
????NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"voice.caf"];
????//NSLog(@"filePath=========================%@",filePath);
????self.recordFileName = filePath;
????NSURL *url = [NSURL fileURLWithPath:filePath];
????
????AVAudioRecorder *recorder = [[AVAudioRecorder alloc] initWithURL:url settings:recordSettings error:&error];
????mRecorder = recorder;
????[recorder setDelegate:self];
????[recorder prepareToRecord];
????
????recorder.meteringEnabled = YES;
????
????BOOL audioHWAvailable = [[AVAudioSession sharedInstance] inputIsAvailable];
????
????// start recording
????[recorder recordForDuration:(NSTimeInterval) 3];
}


播放相对简单:

- (IBAction) play:(id)sender
{
????NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
????AVAudioSession *audioSession = [AVAudioSession sharedInstance];
????[[AVAudioSession sharedInstance] setDelegate:self];
????NSError *error = nil;
????BOOL b = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&error];
//????if(b){
//????????NSLog(@"====================%d",b);
//????}else {
//????????NSLog(@"error=================%@",error);
//????}
????
????b = [audioSession setActive:YES error:&error];
//????if(b){
//????????NSLog(@"====================%d",b);
//????}else {
//????????NSLog(@"error=================%@",error);
//????}
????
????NSURL *url = [NSURL fileURLWithPath:self.recordFileName];
????//NSLog(@"url============================%@",url);
????AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
????player.meteringEnabled = YES;
????player.volume = 1.0;
????player.delegate = self;
????[player prepareToPlay];
????[player play];
????[pool release];
}

  相关解决方案