美文网首页UI进价
iOS 根据音乐来变动闪光灯和闪屏

iOS 根据音乐来变动闪光灯和闪屏

作者: 75cba68968ad | 来源:发表于2018-07-03 15:22 被阅读59次

前段时间一朋友需要实现该功能,其实实现起来不难,下面是实现效果

提示:模拟器看不到效果,需要真机才能看到效果

demo代码下载地址

2018-07-03 14_42_16.gif

闪光灯的开启与关闭

//开启闪光灯
- (void)openFlash{
    
    AVSession = [[AVCaptureSession alloc]init];
    device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    [device lockForConfiguration:nil];//此处以一定要调用这个方法不然程序运行到这里会崩溃
    [device setTorchMode:AVCaptureTorchModeOn];
    [device setFlashMode:AVCaptureFlashModeOn];
    [device unlockForConfiguration];
    [AVSession startRunning];
    
}
//关闭闪光灯
- (void)closeFlash{
    
    AVSession = [[AVCaptureSession alloc]init];
    device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    [device lockForConfiguration:nil];
    [device setTorchMode:AVCaptureTorchModeOff];
    [device setFlashMode:AVCaptureFlashModeOff];
    [device unlockForConfiguration];
    [AVSession stopRunning];
    AVSession = nil;    //置空
    device = nil;       //置空
}

屏幕亮度改变

- (void)changeScreenBright:(float)value
{
    if (self.screnSwitch.on) {
        [[UIScreen mainScreen] setBrightness:value];//修改屏幕亮度
    }
    
}

音乐频率计算

_vodioTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(vodiotimerFire:) userInfo:nil repeats:YES];
    [_vodioTimer fire];

//定时器事件
- (void)vodiotimerFire:(NSTimer *)sender{
    
    self.musicPlayer.meteringEnabled = YES;
    [self.musicPlayer updateMeters];
    
    
    float   level;                // The linear 0.0 .. 1.0 value we need.
    float   minDecibels = -80.0f; // Or use -60dB, which I measured in a silent room.
    float   decibels    = [self.musicPlayer averagePowerForChannel:0];
    
    if (decibels < minDecibels)
    {
        level = 0.0f;
    }
    else if (decibels >= 0.0f)
    {
        level = 1.0f;
    }
    else
    {
        float   root            = 2.0f;
        float   minAmp          = powf(10.0f, 0.05f * minDecibels);
        float   inverseAmpRange = 1.0f / (1.0f - minAmp);
        float   amp             = powf(10.0f, 0.05f * decibels);
        float   adjAmp          = (amp - minAmp) * inverseAmpRange;
        
        level = powf(adjAmp, 1.0f / root);
    }
    
    /* level 范围[0 ~ 1], 转为[0 ~120] 之间 */
    NSInteger newLevel = (NSInteger)(level * 120);
    NSLog(@"level== %d",newLevel);
    if (newLevel == 0) {
        self.oldLevel = newLevel;
    }
    
    NSInteger spaceLevel = newLevel - self.oldLevel;
    if (abs(spaceLevel) >= 10) {
        self.oldLevel = newLevel;
        
        if (self.lampSwitch.on) {
            [self openFlash];
            [self closeFlash];
        }
        
        float currentBright = 1- (newLevel / 120.0);
        [self changeScreenBright:currentBright];
        
        
    } else {
        [self changeScreenBright:self.defaultScreenBright];
    }
    
    
}

demo代码下载地址

相关文章

网友评论

    本文标题:iOS 根据音乐来变动闪光灯和闪屏

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