AudioPlayer是一個基於AVAudioStreamer的在線音樂播放軟件。
https://github.com/marshluca/AudioPlayer
首先將歌曲信息存儲在NSArray中:
itemArray = [[NSArray arrayWithObjects: [NSDictionary dictionaryWithObjectsAndKeys:@"溫柔", @"song", @"五月天", @"artise", @"http://y1.eoews.com/assets/ringtones/2012/5/18/34049/oiuxsvnbtxks7a0tg6xpdo66exdhi8h0bplp7twp.mp3", @"url", nil], [NSDictionary dictionaryWithObjectsAndKeys:@"今天", @"song", @"劉德華", @"artise", @"http://y1.eoews.com/assets/ringtones/2012/5/18/34045/hi4dwfmrxm2citwjcc5841z3tiqaeeoczhbtfoex.mp3", @"url", nil], [NSDictionary dictionaryWithObjectsAndKeys:@"K歌之王", @"song", @"陳奕迅", @"artise", @"http://y1.eoews.com/assets/ringtones/2012/5/17/34031/axiddhql6nhaegcofs4hgsjrllrcbrf175oyjuv0.mp3", @"url", nil], [NSDictionary dictionaryWithObjectsAndKeys:@"知足", @"song", @"五月天", @"artise", @"http://y1.eoews.com/assets/ringtones/2012/5/17/34016/eeemlurxuizy6nltxf2u1yris3kpvdokwhddmeb0.mp3", @"url", nil], [NSDictionary dictionaryWithObjectsAndKeys:@"桔子香水", @"song", @"任賢齊", @"artise", @"http://y1.eoews.com/assets/ringtones/2012/6/29/36195/mx8an3zgp2k4s5aywkr7wkqtqj0dh1vxcvii287a.mp3", @"url", nil], nil] retain];
然后在播放的時候:
- (void)playAudio:(AudioButton *)button { NSInteger index = button.tag; NSDictionary *item = [itemArray objectAtIndex:index]; if (_audioPlayer == nil) { _audioPlayer = [[AudioPlayer alloc] init]; } if ([_audioPlayer.button isEqual:button]) { [_audioPlayer play]; } else { [_audioPlayer stop]; _audioPlayer.button = button; _audioPlayer.url = [NSURL URLWithString:[item objectForKey:@"url"]]; [_audioPlayer play]; } }
在[_audioPlayer play]內部,使歌曲的url初始化AudioStreamer,並用NSTimer設置一個每0.1秒調用一次的方法來更新歌曲的播放進度。然后注冊一個播放狀態變化的通知。
- (void)play { if (!streamer) { self.streamer = [[AudioStreamer alloc] initWithURL:self.url]; // set up display updater NSInvocation *invocation = [NSInvocation invocationWithMethodSignature: [self methodSignatureForSelector:@selector(updateProgress)]]; [invocation setSelector:@selector(updateProgress)]; [invocation setTarget:self]; timer = [NSTimer scheduledTimerWithTimeInterval:0.1 invocation:invocation repeats:YES]; // register the streamer on notification [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackStateChanged:) name:ASStatusChangedNotification object:streamer]; } if ([streamer isPlaying]) { [streamer pause]; } else { [streamer start]; } }