音樂後臺播放代碼

共有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];
     }*/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章