IOS 控制音量并实现后台播放音乐

一、添加音量控制


    1、首先我们可以使用系统自带的 MPVolumeView,需导入framework :MediaPlayer.framework

    MPVolumeView *volumeView = [ [MPVolumeView alloc] init];
    volumeView.frame=CGRectMake(47, 349, 227, 23);
    [volumeView setShowsVolumeSlider:YES];
    [volumeView setShowsRouteButton:YES];
    [volumeView sizeToFit];
    [self.view addSubview:volumeView];

  2、通过 UISlider 和 MPMusicPlayerController 来自定义一个组件

@property(nonatomic,strong) UISlider *volumeSliders;
    self.volumeSliders=[[UISlider alloc]init];
    self.volumeSliders.frame=CGRectMake(47, 349, 227, 23);
    [self.volumeSliders addTarget:self action:@selector(changeVolumes:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.volumeSliders];
- (IBAction)changeVolumes:(id)sender {
    float volume=[[NSString stringWithFormat:@"%.1f",self.volumeSliders.value] floatValue] ;
    [[MPMusicPlayerController applicationMusicPlayer] setVolume:volume];
}

二、后台播放音乐


在Supporting Files-->Info.plist文件里添加 Required background modes --> App plays audio



在合适的地方加上:

 [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; //后台播放

demo地址:https://github.com/marujun/RadioStation/blob/master/RadioStation/ViewController.m





你可能感兴趣的:(iOS)