iOSで音楽を再生する

7615 ワード

http://www.jianshu.com/p/ce279bc773dd
 
まず、Streaming Kitのリンクを入れます.
簡単な再生使用例は、オープンソースの著者のデモデモデモデモを見ることができます.
全体のプレーヤーはUIやデータに関わっていますので、全部取ってdemoになりません.ここにTIPSを並べて、皆さんに助けてもらいたいです.
歌の再生形式はこう書きます.
.h :
/**
       
 */
typedef enum : NSUInteger {
    MBAudioPlayTypeCircle,  //    
    MBAudioPlayTypeRandom,  //    
    MBAudioPlayTypeOneMusic,//    
    MBAudioPlayTypeNoNext,  //      
} MBAudioPlayType;

.m :

/**
 *     
 */
- (void)playNextMusic
{
 switch (self.playType) {
        case MBAudioPlayTypeCircle:
        {
            //    
            _nowMusicLocal++;
            if (_nowMusicLocal >= [self allLocal]) {
                _nowMusicLocal = 0;
            }
            [self playMusic];

        }
            break;
        case MBAudioPlayTypeRandom:
        {
            //    
            [self randomWithTimes:5];

            if (_nowMusicLocal >= [self allLocal]) {
                _nowMusicLocal = 0;
            }
            [self playMusic];

        }
            break;
        case MBAudioPlayTypeOneMusic:
        {
            //    
            [self playMusicWithInfo];
        }
            break;
        case MBAudioPlayTypeNoNext:
        {
            //      

        }
            break;
        default:
            break;
    }

}

#pragma mark -        
/**
 *      
 *
 *  @param num     
 */
-(void)randomWithTimes:(NSInteger)num
{
    NSInteger randomMusic = arc4random() % [self allLocal];

    DLog(@"    :%ld",(long)randomMusic);

    if (_nowMusicLocal == randomMusic && [self allLocal] != 1) {
        //       
        if (num != 0) {
            num--;
            [self randomWithTimes:num];
            return;
        }else
        {
            randomMusic++;
            //       ,       (     )
            _nowMusicLocal = randomMusic;
        }
    }
    else
    {
        //    
        _nowMusicLocal = randomMusic;
    }
}
このランダムアルゴリズムはよく書いていますが、なんとか使えますよね.
バックグラウンド再生権限を取得
targt-capabilities-background modesでaudio and airplayをオープンします.
AppDelegateでは
#import 
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    xxxxx;

NSError* error;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
}
一番重要なのは、プログラムをかける時に、手動で権限を持つものです.
- (void)applicationWillResignActive:(UIApplication *)application
{

    DLog(@"

。。

"); //MBAudioPlayer , , , , if ([MBAudioPlayer shareInstance].audioPlayer.state == STKAudioPlayerStatePlaying||[MBAudioPlayer shareInstance].audioPlayer.state == STKAudioPlayerStateBuffering||[MBAudioPlayer shareInstance].audioPlayer.state == STKAudioPlayerStatePaused ||[MBAudioPlayer shareInstance].audioPlayer.state == STKAudioPlayerStateStopped) { // , , 。 [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; [self becomeFirstResponder]; // [[MBAudioPlayer shareInstance] decideTimerWithType:MBAudioTimerStartBackground andBeginState:YES]; [[MBAudioPlayer shareInstance] configNowPlayingInfoCenter]; } else { [[UIApplication sharedApplication] endReceivingRemoteControlEvents]; [self resignFirstResponder]; // [[MBAudioPlayer shareInstance] decideTimerWithType:MBAudioTimerStartBackground andBeginState:NO]; } }
ロック画面の場合は、コンソール、ロック画面情報(タイマー呼び出し)を更新します.
#pragma mark -     

/**
 *        
 */
-(void)configNowPlayingInfoCenter
{

    if (self.nowPlayingMusicInfo == nil) {
        return;
    }


    @autoreleasepool {

        NSDictionary *info = self.nowPlayingMusicInfo;


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

        //    
        [dict setObject:[info ObjectNullForKey:@"title"] forKey:MPMediaItemPropertyTitle];

        //   
        [dict setObject:[info ObjectNullForKey:@"author"] forKey:MPMediaItemPropertyArtist];

        //   
        //[dict setObject:[info ObjectNullForKey:@"album"] forKey:MPMediaItemPropertyAlbumTitle];

        //     
        NSString *imagePath = [info ObjectNullForKey:@"thumb"];
        imagePath = [NSString stringWithFormat:@"EGOImageLoader-%lu", (unsigned long)[[imagePath description] hash]];
        NSString *imageLocalPath = [NSString stringWithFormat:@"%@/%@", EGOCacheDirectory(),imagePath];

        NSData * thumbData = [NSData dataWithContentsOfFile:imageLocalPath];

        if (thumbData != nil) {
            UIImage *image = [UIImage imageWithData:thumbData];
            MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
            [dict setObject:artwork forKey:MPMediaItemPropertyArtwork];
        }else
        {
            // FIXME:      ,   

        }
        //      
        [dict setObject:[NSNumber numberWithDouble:self.audioPlayer.duration] forKey:MPMediaItemPropertyPlaybackDuration];

        //                
        [dict setObject:[NSNumber numberWithDouble:self.audioPlayer.progress] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];

        //                 
        //DLog(@"        :%@
%@",dict,[info ObjectNullForKey:@"title"]); [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict]; } } /** * * * @param receivedEvent */ - (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent { if (receivedEvent.type == UIEventTypeRemoteControl) { switch (receivedEvent.subtype) { case UIEventSubtypeRemoteControlPause: // [self pauseStreamer]; break; case UIEventSubtypeRemoteControlNextTrack: // [self playNextMusic]; break; case UIEventSubtypeRemoteControlPreviousTrack: // [self playPreMusic]; // break; case UIEventSubtypeRemoteControlPlay: // [self pauseStreamer]; break; default: break; } } }
最後に、ロックスクリーンに歌詞が付いている製品は、歌詞とアルバムの写真を合わせて、歌詞の時間によって写真を更新するということです.この製品の需要があれば、この考え方で作ってもいいです.