11 |
12 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | This is free and unencumbered software released into the public domain.
2 |
3 | Anyone is free to copy, modify, publish, use, compile, sell, or
4 | distribute this software, either in source code form or as a compiled
5 | binary, for any purpose, commercial or non-commercial, and by any
6 | means.
7 |
8 | In jurisdictions that recognize copyright laws, the author or authors
9 | of this software dedicate any and all copyright interest in the
10 | software to the public domain. We make this dedication for the benefit
11 | of the public at large and to the detriment of our heirs and
12 | successors. We intend this dedication to be an overt act of
13 | relinquishment in perpetuity of all present and future rights to this
14 | software under copyright law.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22 | OTHER DEALINGS IN THE SOFTWARE.
23 |
24 | For more information, please refer to
25 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ExoplayerExample
2 |
3 | A simple ExoPlayer2 audio example displaying how to play audio files.
4 |
5 |
6 |
Play audio file stored in the filesystem
7 |
Play audio file attached as a resource in the res/raw folder
8 |
Play audio file from a provided web url
9 |
10 |
11 | ## Disclaimer
12 | This example does not target the latest version of either exoplayer or Android SDK. Although it seems to work for most people out of the box, updating it to target the latest versions might break functionality.
13 |
14 | ## Help wanted
15 | This project would require some fresh work, to update it to the latest versions of Android SDK and ExoPlayer library.
16 | If you have time and skills, please make a PR with the updates and I'll do my best to review it asap.
17 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 25
5 | buildToolsVersion "25.0.2"
6 | defaultConfig {
7 | applicationId "com.ak93.exoplayerexample"
8 | minSdkVersion 16
9 | targetSdkVersion 25
10 | versionCode 1
11 | versionName "1.0"
12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
25 | exclude group: 'com.android.support', module: 'support-annotations'
26 | })
27 | compile 'com.android.support:appcompat-v7:25.2.0'
28 | compile 'com.android.support.constraint:constraint-layout:1.0.2'
29 | testCompile 'junit:junit:4.12'
30 |
31 | compile 'com.google.android.exoplayer:exoplayer:r2.2.0'
32 | }
33 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in C:\Android\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/app/src/main/java/com/ak93/exoplayerexample/FileDialog.java:
--------------------------------------------------------------------------------
1 | package com.ak93.exoplayerexample;
2 |
3 | import android.app.Activity;
4 | import android.app.Dialog;
5 | import android.content.DialogInterface;
6 | import android.os.Environment;
7 | import android.support.v7.app.AlertDialog;
8 | import android.util.Log;
9 | import java.io.File;
10 | import java.io.FilenameFilter;
11 | import java.util.ArrayList;
12 | import java.util.List;
13 |
14 | class FileDialog {
15 | private static final String PARENT_DIR = "..";
16 | private final String TAG = getClass().getName();
17 | private String[] fileList;
18 | private File currentPath;
19 | public interface FileSelectedListener {
20 | void fileSelected(File file);
21 | }
22 | public interface DirectorySelectedListener {
23 | void directorySelected(File directory);
24 | }
25 | private ListenerList fileListenerList = new ListenerList();
26 | private ListenerList dirListenerList = new ListenerList();
27 | private final Activity activity;
28 | private boolean selectDirectoryOption;
29 | private String fileEndsWith;
30 |
31 | /**
32 | * @param activity
33 | * @param initialPath
34 | */
35 | public FileDialog(Activity activity, File initialPath) {
36 | this(activity, initialPath, null);
37 | }
38 |
39 | public FileDialog(Activity activity, File initialPath, String fileEndsWith) {
40 | this.activity = activity;
41 | setFileEndsWith(fileEndsWith);
42 | if (!initialPath.exists()) initialPath = Environment.getExternalStorageDirectory();
43 | loadFileList(initialPath);
44 | }
45 |
46 | /**
47 | * @return file dialog
48 | */
49 | public Dialog createFileDialog() {
50 | Dialog dialog = null;
51 | AlertDialog.Builder builder = new AlertDialog.Builder(activity);
52 |
53 | builder.setTitle(currentPath.getPath());
54 | if (selectDirectoryOption) {
55 | builder.setPositiveButton("Select directory", new DialogInterface.OnClickListener() {
56 | public void onClick(DialogInterface dialog, int which) {
57 | Log.d(TAG, currentPath.getPath());
58 | fireDirectorySelectedEvent(currentPath);
59 | }
60 | });
61 | }
62 |
63 | builder.setItems(fileList, new DialogInterface.OnClickListener() {
64 | public void onClick(DialogInterface dialog, int which) {
65 | String fileChosen = fileList[which];
66 | File chosenFile = getChosenFile(fileChosen);
67 | if (chosenFile.isDirectory()) {
68 | loadFileList(chosenFile);
69 | dialog.cancel();
70 | dialog.dismiss();
71 | showDialog();
72 | } else fireFileSelectedEvent(chosenFile);
73 | }
74 | });
75 |
76 | dialog = builder.show();
77 | return dialog;
78 | }
79 |
80 |
81 | public void addFileListener(FileSelectedListener listener) {
82 | fileListenerList.add(listener);
83 | }
84 |
85 | public void removeFileListener(FileSelectedListener listener) {
86 | fileListenerList.remove(listener);
87 | }
88 |
89 | public void setSelectDirectoryOption(boolean selectDirectoryOption) {
90 | this.selectDirectoryOption = selectDirectoryOption;
91 | }
92 |
93 | public void addDirectoryListener(DirectorySelectedListener listener) {
94 | dirListenerList.add(listener);
95 | }
96 |
97 | public void removeDirectoryListener(DirectorySelectedListener listener) {
98 | dirListenerList.remove(listener);
99 | }
100 |
101 | /**
102 | * Show file dialog
103 | */
104 | public void showDialog() {
105 | createFileDialog().show();
106 | }
107 |
108 | private void fireFileSelectedEvent(final File file) {
109 | fileListenerList.fireEvent(new ListenerList.FireHandler() {
110 | public void fireEvent(FileSelectedListener listener) {
111 | listener.fileSelected(file);
112 | }
113 | });
114 | }
115 |
116 | private void fireDirectorySelectedEvent(final File directory) {
117 | dirListenerList.fireEvent(new ListenerList.FireHandler() {
118 | public void fireEvent(DirectorySelectedListener listener) {
119 | listener.directorySelected(directory);
120 | }
121 | });
122 | }
123 |
124 | private void loadFileList(File path) {
125 | this.currentPath = path;
126 | List r = new ArrayList<>();
127 | if (path.exists()) {
128 | if (path.getParentFile() != null) r.add(PARENT_DIR);
129 | FilenameFilter filter = new FilenameFilter() {
130 | public boolean accept(File dir, String filename) {
131 | File sel = new File(dir, filename);
132 | if (!sel.canRead()) return false;
133 | if (selectDirectoryOption) return sel.isDirectory();
134 | else {
135 | boolean endsWith = fileEndsWith != null ? filename.toLowerCase().endsWith(fileEndsWith) : true;
136 | return endsWith || sel.isDirectory();
137 | }
138 | }
139 | };
140 | String[] fileList1 = path.list(filter);
141 | for (String file : fileList1) {
142 | r.add(file);
143 | }
144 | }
145 | fileList = (String[]) r.toArray(new String[]{});
146 | }
147 |
148 | private File getChosenFile(String fileChosen) {
149 | if (fileChosen.equals(PARENT_DIR)) return currentPath.getParentFile();
150 | else return new File(currentPath, fileChosen);
151 | }
152 |
153 | private void setFileEndsWith(String fileEndsWith) {
154 | this.fileEndsWith = fileEndsWith != null ? fileEndsWith.toLowerCase() : fileEndsWith;
155 | }
156 | }
157 |
158 | class ListenerList {
159 | private List listenerList = new ArrayList();
160 |
161 | public interface FireHandler {
162 | void fireEvent(L listener);
163 | }
164 |
165 | public void add(L listener) {
166 | listenerList.add(listener);
167 | }
168 |
169 | public void fireEvent(FireHandler fireHandler) {
170 | List copy = new ArrayList(listenerList);
171 | for (L l : copy) {
172 | fireHandler.fireEvent(l);
173 | }
174 | }
175 |
176 | public void remove(L listener) {
177 | listenerList.remove(listener);
178 | }
179 |
180 | public List getListenerList() {
181 | return listenerList;
182 | }
183 | }
184 |
--------------------------------------------------------------------------------
/app/src/main/java/com/ak93/exoplayerexample/MByteArrayDataSource.java:
--------------------------------------------------------------------------------
1 | package com.ak93.exoplayerexample;
2 |
3 | import android.net.Uri;
4 |
5 | import com.google.android.exoplayer2.C;
6 | import com.google.android.exoplayer2.upstream.DataSource;
7 | import com.google.android.exoplayer2.upstream.DataSpec;
8 |
9 | import java.io.IOException;
10 |
11 | /**
12 | * Created by Anže Kožar on 12.3.2017.
13 | */
14 |
15 | public class MByteArrayDataSource implements DataSource {
16 |
17 | private final byte[] data;
18 |
19 | private Uri uri;
20 | private int readPosition;
21 | private int bytesRemaining;
22 |
23 | public MByteArrayDataSource(byte[] data){
24 | this.data = data;
25 | readPosition = 0;
26 | bytesRemaining = data.length;
27 | }
28 |
29 | @Override
30 | public long open(DataSpec dataSpec) throws IOException {
31 | uri = dataSpec.uri;
32 | readPosition = (int) dataSpec.position;
33 | bytesRemaining = (int) ((dataSpec.length == C.LENGTH_UNSET)
34 | ? (data.length - dataSpec.position) : dataSpec.length);
35 | if (bytesRemaining <= 0 || readPosition + bytesRemaining > data.length) {
36 | throw new IOException("Unsatisfiable range: [" + readPosition + ", " + dataSpec.length
37 | + "], length: " + data.length);
38 | }
39 | return bytesRemaining;
40 | }
41 |
42 | @Override
43 | public int read(byte[] buffer, int offset, int readLength) throws IOException {
44 | if (readLength == 0) {
45 | return 0;
46 | } else if (bytesRemaining == 0) {
47 | return C.RESULT_END_OF_INPUT;
48 | }
49 |
50 | readLength = Math.min(readLength, bytesRemaining);
51 | System.arraycopy(data, readPosition, buffer, offset, readLength);
52 | readPosition += readLength;
53 | bytesRemaining -= readLength;
54 | return readLength;
55 | }
56 |
57 | @Override
58 | public Uri getUri() {
59 | return uri;
60 | }
61 |
62 | @Override
63 | public void close() throws IOException {
64 | uri = null;
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/app/src/main/java/com/ak93/exoplayerexample/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.ak93.exoplayerexample;
2 |
3 | import android.net.Uri;
4 | import android.os.Handler;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.os.Bundle;
7 | import android.util.Log;
8 | import android.view.View;
9 | import android.widget.ImageButton;
10 | import android.widget.SeekBar;
11 | import android.widget.TextView;
12 | import com.google.android.exoplayer2.DefaultLoadControl;
13 | import com.google.android.exoplayer2.ExoPlaybackException;
14 | import com.google.android.exoplayer2.ExoPlayer;
15 | import com.google.android.exoplayer2.ExoPlayerFactory;
16 | import com.google.android.exoplayer2.LoadControl;
17 | import com.google.android.exoplayer2.SimpleExoPlayer;
18 | import com.google.android.exoplayer2.Timeline;
19 | import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
20 | import com.google.android.exoplayer2.extractor.ExtractorsFactory;
21 | import com.google.android.exoplayer2.source.ExtractorMediaSource;
22 | import com.google.android.exoplayer2.source.MediaSource;
23 | import com.google.android.exoplayer2.source.TrackGroupArray;
24 | import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
25 | import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
26 | import com.google.android.exoplayer2.trackselection.TrackSelector;
27 | import com.google.android.exoplayer2.upstream.ByteArrayDataSource;
28 | import com.google.android.exoplayer2.upstream.DataSource;
29 | import com.google.android.exoplayer2.upstream.DataSpec;
30 | import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
31 | import com.google.android.exoplayer2.upstream.FileDataSource;
32 | import com.google.android.exoplayer2.upstream.RawResourceDataSource;
33 | import com.google.android.exoplayer2.util.Util;
34 |
35 | import java.io.File;
36 | import java.util.Formatter;
37 | import java.util.Locale;
38 |
39 | public class MainActivity extends AppCompatActivity {
40 |
41 | private SimpleExoPlayer exoPlayer;
42 | private ExoPlayer.EventListener eventListener = new ExoPlayer.EventListener() {
43 | @Override
44 | public void onTimelineChanged(Timeline timeline, Object manifest) {
45 | Log.i(TAG,"onTimelineChanged");
46 | }
47 |
48 | @Override
49 | public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
50 | Log.i(TAG,"onTracksChanged");
51 | }
52 |
53 | @Override
54 | public void onLoadingChanged(boolean isLoading) {
55 | Log.i(TAG,"onLoadingChanged");
56 | }
57 |
58 | @Override
59 | public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
60 | Log.i(TAG,"onPlayerStateChanged: playWhenReady = "+String.valueOf(playWhenReady)
61 | +" playbackState = "+playbackState);
62 | switch (playbackState){
63 | case ExoPlayer.STATE_ENDED:
64 | Log.i(TAG,"Playback ended!");
65 | //Stop playback and return to start position
66 | setPlayPause(false);
67 | exoPlayer.seekTo(0);
68 | break;
69 | case ExoPlayer.STATE_READY:
70 | Log.i(TAG,"ExoPlayer ready! pos: "+exoPlayer.getCurrentPosition()
71 | +" max: "+stringForTime((int)exoPlayer.getDuration()));
72 | setProgress();
73 | break;
74 | case ExoPlayer.STATE_BUFFERING:
75 | Log.i(TAG,"Playback buffering!");
76 | break;
77 | case ExoPlayer.STATE_IDLE:
78 | Log.i(TAG,"ExoPlayer idle!");
79 | break;
80 | }
81 | }
82 |
83 | @Override
84 | public void onPlayerError(ExoPlaybackException error) {
85 | Log.i(TAG,"onPlaybackError: "+error.getMessage());
86 | }
87 |
88 | @Override
89 | public void onPositionDiscontinuity() {
90 | Log.i(TAG,"onPositionDiscontinuity");
91 | }
92 | };
93 |
94 | private SeekBar seekPlayerProgress;
95 | private Handler handler;
96 | private ImageButton btnPlay;
97 | private TextView txtCurrentTime, txtEndTime;
98 | private boolean isPlaying = false;
99 |
100 | private static final String TAG = "MainActivity";
101 |
102 | @Override
103 | protected void onCreate(Bundle savedInstanceState) {
104 | super.onCreate(savedInstanceState);
105 | setContentView(R.layout.activity_main);
106 |
107 |
108 | File f_ext_files_dir = getExternalFilesDir(null);
109 |
110 | FileDialog fileDialog = new FileDialog(this, f_ext_files_dir, "");
111 | fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
112 | @Override
113 | public void fileSelected(File file) {
114 | Log.i("File selected:",file.getAbsolutePath());
115 | prepareExoPlayerFromFileUri(Uri.fromFile(file));
116 |
117 | /*
118 | try {
119 | FileInputStream inputStream = new FileInputStream(file);
120 | byte[] fileData = new byte[(int)file.length()];
121 | Log.i(TAG,"Data before read: "+fileData.length);
122 | int bytesRead = inputStream.read(fileData);
123 | Log.i(TAG,"Bytes read: "+bytesRead);
124 | if(bytesRead>0) {
125 | prepareExoPlayerFromByteArray(fileData);
126 | }
127 | } catch (FileNotFoundException e) {
128 | e.printStackTrace();
129 | } catch (IOException e) {
130 | e.printStackTrace();
131 | }
132 | */
133 | }
134 | });
135 | //fileDialog.showDialog();
136 |
137 | //prepareExoPlayerFromRawResourceUri(RawResourceDataSource.buildRawResourceUri(R.raw.audio));
138 |
139 | prepareExoPlayerFromURL(Uri.parse("https://github.com/nzkozar/ExoplayerExample/blob/master/sample.m4a?raw=true"));
140 | }
141 |
142 | //TODO
143 | private void prepareExoPlayerFromByteArray(byte[] data){
144 | exoPlayer = ExoPlayerFactory.newSimpleInstance(this, new DefaultTrackSelector(null), new DefaultLoadControl());
145 | exoPlayer.addListener(eventListener);
146 |
147 | final MByteArrayDataSource byteArrayDataSource = new MByteArrayDataSource(data);
148 | Log.i(TAG,"ByteArrayDataSource constructed.");
149 | /*
150 | DataSpec dataSpec = new DataSpec(byteArrayDataSource.getUri());
151 | try {
152 | byteArrayDataSource.open(dataSpec);
153 | } catch (IOException e) {
154 | e.printStackTrace();
155 | }
156 | */
157 |
158 | DataSource.Factory factory = new DataSource.Factory() {
159 | @Override
160 | public DataSource createDataSource() {
161 | return byteArrayDataSource;
162 | }
163 | };
164 | Log.i(TAG,"DataSource.Factory constructed.");
165 |
166 | MediaSource audioSource = new ExtractorMediaSource(byteArrayDataSource.getUri(),
167 | factory, new DefaultExtractorsFactory(),null,null);
168 | Log.i(TAG,"Audio source constructed.");
169 | exoPlayer.prepare(audioSource);
170 | initMediaControls();
171 | }
172 |
173 | /**
174 | * Prepares exoplayer for audio playback from a local file
175 | * @param uri
176 | */
177 | private void prepareExoPlayerFromFileUri(Uri uri){
178 | exoPlayer = ExoPlayerFactory.newSimpleInstance(this, new DefaultTrackSelector(null), new DefaultLoadControl());
179 | exoPlayer.addListener(eventListener);
180 |
181 | DataSpec dataSpec = new DataSpec(uri);
182 | final FileDataSource fileDataSource = new FileDataSource();
183 | try {
184 | fileDataSource.open(dataSpec);
185 | } catch (FileDataSource.FileDataSourceException e) {
186 | e.printStackTrace();
187 | }
188 |
189 | DataSource.Factory factory = new DataSource.Factory() {
190 | @Override
191 | public DataSource createDataSource() {
192 | return fileDataSource;
193 | }
194 | };
195 | MediaSource audioSource = new ExtractorMediaSource(fileDataSource.getUri(),
196 | factory, new DefaultExtractorsFactory(), null, null);
197 |
198 | exoPlayer.prepare(audioSource);
199 | initMediaControls();
200 | }
201 |
202 |
203 | /**
204 | * Prepares exoplayer for audio playback from a remote URL audiofile. Should work with most
205 | * popular audiofile types (.mp3, .m4a,...)
206 | * @param uri Provide a Uri in a form of Uri.parse("http://blabla.bleble.com/blublu.mp3)
207 | */
208 | private void prepareExoPlayerFromURL(Uri uri){
209 |
210 | TrackSelector trackSelector = new DefaultTrackSelector();
211 |
212 | LoadControl loadControl = new DefaultLoadControl();
213 |
214 | exoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector, loadControl);
215 |
216 | DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(this, Util.getUserAgent(this, "exoplayer2example"), null);
217 | ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
218 | MediaSource audioSource = new ExtractorMediaSource(uri, dataSourceFactory, extractorsFactory, null, null);
219 | exoPlayer.addListener(eventListener);
220 |
221 | exoPlayer.prepare(audioSource);
222 | initMediaControls();
223 | }
224 |
225 | private void prepareExoPlayerFromRawResourceUri(Uri uri){
226 | exoPlayer = ExoPlayerFactory.newSimpleInstance(this, new DefaultTrackSelector(null), new DefaultLoadControl());
227 | exoPlayer.addListener(eventListener);
228 |
229 | DataSpec dataSpec = new DataSpec(uri);
230 | final RawResourceDataSource rawResourceDataSource = new RawResourceDataSource(this);
231 | try {
232 | rawResourceDataSource.open(dataSpec);
233 | } catch (RawResourceDataSource.RawResourceDataSourceException e) {
234 | e.printStackTrace();
235 | }
236 |
237 | DataSource.Factory factory = new DataSource.Factory() {
238 | @Override
239 | public DataSource createDataSource() {
240 | return rawResourceDataSource;
241 | }
242 | };
243 |
244 | MediaSource audioSource = new ExtractorMediaSource(rawResourceDataSource.getUri(),
245 | factory, new DefaultExtractorsFactory(), null, null);
246 |
247 | exoPlayer.prepare(audioSource);
248 | initMediaControls();
249 | }
250 |
251 | private void initMediaControls() {
252 | initPlayButton();
253 | initSeekBar();
254 | initTxtTime();
255 | }
256 |
257 | private void initPlayButton() {
258 | btnPlay = (ImageButton) findViewById(R.id.btnPlay);
259 | btnPlay.requestFocus();
260 | btnPlay.setOnClickListener(new View.OnClickListener() {
261 | @Override
262 | public void onClick(View view) {
263 | setPlayPause(!isPlaying);
264 | }
265 | });
266 | }
267 |
268 | /**
269 | * Starts or stops playback. Also takes care of the Play/Pause button toggling
270 | * @param play True if playback should be started
271 | */
272 | private void setPlayPause(boolean play){
273 | isPlaying = play;
274 | exoPlayer.setPlayWhenReady(play);
275 | if(!isPlaying){
276 | btnPlay.setImageResource(android.R.drawable.ic_media_play);
277 | }else{
278 | setProgress();
279 | btnPlay.setImageResource(android.R.drawable.ic_media_pause);
280 | }
281 | }
282 |
283 | private void initTxtTime() {
284 | txtCurrentTime = (TextView) findViewById(R.id.time_current);
285 | txtEndTime = (TextView) findViewById(R.id.player_end_time);
286 | }
287 |
288 | private String stringForTime(int timeMs) {
289 | StringBuilder mFormatBuilder;
290 | Formatter mFormatter;
291 | mFormatBuilder = new StringBuilder();
292 | mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
293 | int totalSeconds = timeMs / 1000;
294 |
295 | int seconds = totalSeconds % 60;
296 | int minutes = (totalSeconds / 60) % 60;
297 | int hours = totalSeconds / 3600;
298 |
299 | mFormatBuilder.setLength(0);
300 | if (hours > 0) {
301 | return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
302 | } else {
303 | return mFormatter.format("%02d:%02d", minutes, seconds).toString();
304 | }
305 | }
306 |
307 | private void setProgress() {
308 | seekPlayerProgress.setProgress(0);
309 | seekPlayerProgress.setMax((int) exoPlayer.getDuration()/1000);
310 | txtCurrentTime.setText(stringForTime((int)exoPlayer.getCurrentPosition()));
311 | txtEndTime.setText(stringForTime((int)exoPlayer.getDuration()));
312 |
313 | if(handler == null)handler = new Handler();
314 | //Make sure you update Seekbar on UI thread
315 | handler.post(new Runnable() {
316 | @Override
317 | public void run() {
318 | if (exoPlayer != null && isPlaying) {
319 | seekPlayerProgress.setMax((int) exoPlayer.getDuration()/1000);
320 | int mCurrentPosition = (int) exoPlayer.getCurrentPosition() / 1000;
321 | seekPlayerProgress.setProgress(mCurrentPosition);
322 | txtCurrentTime.setText(stringForTime((int)exoPlayer.getCurrentPosition()));
323 | txtEndTime.setText(stringForTime((int)exoPlayer.getDuration()));
324 |
325 | handler.postDelayed(this, 1000);
326 | }
327 | }
328 | });
329 | }
330 |
331 | private void initSeekBar() {
332 | seekPlayerProgress = (SeekBar) findViewById(R.id.mediacontroller_progress);
333 | seekPlayerProgress.requestFocus();
334 |
335 | seekPlayerProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
336 | @Override
337 | public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
338 | if (!fromUser) {
339 | // We're not interested in programmatically generated changes to
340 | // the progress bar's position.
341 | return;
342 | }
343 |
344 | exoPlayer.seekTo(progress*1000);
345 | }
346 |
347 | @Override
348 | public void onStartTrackingTouch(SeekBar seekBar) {
349 |
350 | }
351 |
352 | @Override
353 | public void onStopTrackingTouch(SeekBar seekBar) {
354 |
355 | }
356 | });
357 |
358 | seekPlayerProgress.setMax(0);
359 | seekPlayerProgress.setMax((int) exoPlayer.getDuration()/1000);
360 |
361 | }
362 | }
363 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 |
17 |
18 |
24 |
25 |
28 |
29 |
30 |
31 |
35 |
36 |
47 |
48 |
54 |
55 |
66 |
67 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nzkozar/ExoplayerExample/82b88be8c6a97e7cb8b7eef7afe9b39445984322/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nzkozar/ExoplayerExample/82b88be8c6a97e7cb8b7eef7afe9b39445984322/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nzkozar/ExoplayerExample/82b88be8c6a97e7cb8b7eef7afe9b39445984322/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nzkozar/ExoplayerExample/82b88be8c6a97e7cb8b7eef7afe9b39445984322/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nzkozar/ExoplayerExample/82b88be8c6a97e7cb8b7eef7afe9b39445984322/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nzkozar/ExoplayerExample/82b88be8c6a97e7cb8b7eef7afe9b39445984322/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nzkozar/ExoplayerExample/82b88be8c6a97e7cb8b7eef7afe9b39445984322/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nzkozar/ExoplayerExample/82b88be8c6a97e7cb8b7eef7afe9b39445984322/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nzkozar/ExoplayerExample/82b88be8c6a97e7cb8b7eef7afe9b39445984322/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nzkozar/ExoplayerExample/82b88be8c6a97e7cb8b7eef7afe9b39445984322/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/raw/audio.mp3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nzkozar/ExoplayerExample/82b88be8c6a97e7cb8b7eef7afe9b39445984322/app/src/main/res/raw/audio.mp3
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Exoplayer Example
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.3.1'
9 |
10 | // NOTE: Do not place your application dependencies here; they belong
11 | // in the individual module build.gradle files
12 | }
13 | }
14 |
15 | allprojects {
16 | repositories {
17 | jcenter()
18 | }
19 | }
20 |
21 | task clean(type: Delete) {
22 | delete rootProject.buildDir
23 | }
24 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nzkozar/ExoplayerExample/82b88be8c6a97e7cb8b7eef7afe9b39445984322/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Mar 10 12:02:13 CET 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/sample.m4a:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nzkozar/ExoplayerExample/82b88be8c6a97e7cb8b7eef7afe9b39445984322/sample.m4a
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------