美文网首页
解决iOS12.1播放不了本地的音频

解决iOS12.1播放不了本地的音频

作者: Cathy范 | 来源:发表于2019-02-19 14:46 被阅读58次

    最近项目测试时发现一个问题,iOS12.1播放不了本地的音频,百度搜索了,有几种解决方案也是不错的,不过个人觉得有点麻烦,于是再拿手机多测试了两下,发现我启动录音后就可以播放任何一个本地音频了,总结出iOS12.1以上播放本地音频前先初始化一下录音器,便能解决iOS12.1播放不了音频的问题,好吧,直接上代码,如下:

        NSString *version = [UIDevice currentDevice].systemVersion;

        if(version.doubleValue>=12.0) {

            [self intplayforheighsys];

        }else{

     //12.0以下无须处理

        }

    //ios12.1以上要先初始化录音的,才能播放

    -(void)intplayforheighsys{

        //开始录音

        //录音设置

        NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];

        //设置录音格式  AVFormatIDKey==kAudioFormatLinearPCM

        [recordSettingsetValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];

        //设置录音采样率(Hz) 如:AVSampleRateKey==8000/44100/96000(影响音频的质量), 采样率必须要设为11025才能使转化成mp3格式后不会失真

        [recordSettingsetValue:[NSNumber numberWithFloat:11025.0] forKey:AVSampleRateKey];

        //录音通道数  1 或 2 ,要转换成mp3格式必须为双通道

        [recordSettingsetValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];

        //线性采样位数  8、16、24、32

        [recordSettingsetValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];

        //录音的质量

        [recordSettingsetValue:[NSNumber numberWithInt:AVAudioQualityMedium] forKey:AVEncoderAudioQualityKey];

        //存储录音文件

        recordUrl = [NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingString:@"ringRecord.wav"]];

        //初始化

        audioRecorder = [[AVAudioRecorder alloc] initWithURL:recordUrl settings:recordSetting error:nil];

        //开启音量检测

        audioRecorder.meteringEnabled = YES;

        audioSession = [AVAudioSession sharedInstance];//得到AVAudioSession单例对象

        if (![audioRecorder isRecording]) {

            [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];//设置类别,表示该应用同时支持播放和录音

            [audioSession setActive:YES error:nil];//启动音频会话管理,此时会阻断后台音乐的播放.

            [audioRecorder prepareToRecord];

            [audioRecorder peakPowerForChannel:0.0];

            [audioRecorder record];

        }

        [audioRecorderstop];                          //录音停止

        [audioSession setActive:NO error:nil];

    }

    相关文章

      网友评论

          本文标题:解决iOS12.1播放不了本地的音频

          本文链接:https://www.haomeiwen.com/subject/sezxyqtx.html