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

转自: http://xiongzhend.blog.163.com/blog/static/6409850120108821651530/

在 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];
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值