Created
April 20, 2013 13:48
-
-
Save yangyi/5426036 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* sample code, 实现不完整. 可能要用service实现, 但是接口相同 */ | |
| // 先不用去想怎么实现, 先想我在Activity和UI会怎么用 audio player | |
| // 1. 因为需要能够自动切换到下一首, 所以生成播放器需要一个播放列表 | |
| // 2. 在播放的时候, UI需要根据播放器的状态显示不同的UI, 所以需要监听AudioPlayer的状态 | |
| // 3. 因为需要能够播放任意一首歌曲, 需要play(int index) | |
| public class AudioListPlayer { | |
| // 我们在UI上只需要这四个状态, 那么就只监听这些状态 | |
| public static interface AudioPlayerListener { | |
| public void onReady(); // 当缓冲完毕的时候 | |
| public void onProgress(int percentage); | |
| public void onStartBuffer(); // 当音频需要缓冲才能播放的时候 | |
| public void onStop(); // 当播放完毕的时候 | |
| public void onNext(int index); // 当切换到下一首 | |
| } | |
| private AudioPlayerListener audioPlayerListener; | |
| // 因为需要能够自动切换到下一首, 所以生成播放器需要一个播放列表 | |
| private audios; | |
| public AudioListPlayer(List<Audio> audios) { | |
| } | |
| MediaPlayer player; | |
| int playingIndex; | |
| public void play(int index) { | |
| playingIndex = index; | |
| Audio audio = audios.get(index); | |
| String audioUrl = audio.getContentUrl(); | |
| player = new MediaPlayer(); | |
| // init format... and other code.... | |
| player.setDataSource(audioUrl); | |
| player.setOnPreparedListerner(new OnPreparedListener() { | |
| public void onPrepared(MediaPlayer mp) { | |
| audioPlayerListener.onReady(); | |
| } | |
| }); | |
| player.setOnSeekCompletionListener(new OnSeekCompletionListner() { | |
| public void onSeekComplete(MediaPlayer mp) { | |
| audioPlayerListener.onReady() | |
| } | |
| }); | |
| player.setOnCompletionListener(new OnCompletionListener() { | |
| if ( hasNext() ) { | |
| audioPlayerListener.onNext(playingIndex + 1); | |
| playNext(); | |
| } else { | |
| audioPlayerListener.onStop(); | |
| } | |
| }); | |
| player.onStartBuffer(); | |
| player.prepareAsync(); | |
| } | |
| public void seek(int second) { | |
| audioPlayerListener.onStartBuffer(); | |
| player.seekTo(second); | |
| } | |
| public void playNext() { | |
| if (hasNext()) { | |
| play(playingIndex + 1); | |
| } | |
| } | |
| public void playPrevious() { | |
| if (hasPrevious()) { | |
| play(playingIndex - 1); | |
| } | |
| } | |
| private boolean hasPrevious() { | |
| playingIndex > 0; | |
| } | |
| private boolean hasNext() { | |
| playingIndex <= audios.size(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment