后台播放音乐,防止iphone进入休眠,超详细教程(可制作音乐闹钟)

44 篇文章 0 订阅
44 篇文章 0 订阅

//  后台播放音乐


共有4个步骤,一个注意事项

步骤一:在resource文件夹下找到该项目的info.plist添加一个

Required background modes 的数组

并在下面添加一个元素,其值为

App plays audio


步骤二:


需要导入相应的framework和头文件

#import <AudioToolbox/AudioToolbox.h>

#import <AVFoundation/AVFoundation.h>



步骤三:

//禁止程序运行时自动锁屏

        [[UIApplicationsharedApplication]setIdleTimerDisabled:YES];



步骤四:

       AVAudioSession *audioSession = [AVAudioSessionsharedInstance];

       NSError *err =nil;

        [audioSession setCategory :AVAudioSessionCategoryPlayAndRecorderror:&err];

       if(err)

        {

           NSLog(@"audioSession: %@ %d %@", [errdomain], [errcode], [[erruserInfo]description]);

           

        }

        [audioSessionsetActive:YESerror:&err];

        err =nil;

       if(err)

        {

           NSLog(@"audioSession: %@ %d %@", [errdomain], [errcode], [[erruserInfo]description]);

            

        }

        

        

        

        

       NSString * musicFilePath = [[NSBundlemainBundle]pathForResource:@"初音ミク-World Is Mine" ofType:@"mp3"];      //创建音乐文件路径

       NSURL * musicURL= [[NSURLalloc]initFileURLWithPath:musicFilePath];

        

       AVAudioPlayer * thePlayer  = [[AVAudioPlayeralloc]initWithContentsOfURL:musicURLerror:nil];

        

        [thePlayerplay];

        [thePlayersetVolume:1];  //设置音量大小

        thePlayer.numberOfLoops = -1;//设置音乐播放次数  -1为一直循环

        

        [musicURLrelease];

        [thePlayerrelease];


注意事项:

注意模拟器是不能展示后台效果的,不要实现了功能还以为没实现,请用真机测试


//播一半的歌曲退出后台后停止

    /*MPMusicPlayerController *musicPlayer = [MPMusicPlayerController iPodMusicPlayer];

     MPMusicPlaybackState playbackState = musicPlayer.playbackState;

     if (playbackState == MPMusicPlaybackStateStopped || playbackState == MPMusicPlaybackStatePaused) {

     [musicPlayer play];

     } else if (playbackState == MPMusicPlaybackStatePlaying) {

     [musicPlayer pause];

     }*/


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值