androidandroid-videoviewexoplayerandroid-storage

Exoplayer 2: Playing mp4 from cacheDir


I am downloading mp4 from server to cacheDir. Later I want to play this video using Exoplayer. But I am unable to do so.

I used following for playing server Url: (It worked fine)

extractorsFactory = new DefaultExtractorsFactory();
MediaSource mediaSource = new ExtractorMediaSource(Uri.parse(videoURL),
    cacheDataourceFactory, extractorsFactory, null, null);

Local url from cacheDir: (not working)

File file = new File(context.getApplicationContext().getCacheDir(), "/MP4/test.mp4");
extractorsFactory = new DefaultExtractorsFactory();
MediaSource mediaSource = new ExtractorMediaSource(Uri.parse(file.toString(), 
    cacheDataourceFactory, extractorsFactory, null, null);

Solution

  • Try this code:

        File file = new File(context.getApplicationContext().getCacheDir(), "/MP4/test.mp4");        
        Uri uri = Uri.fromFile(file);      
        DataSpec dataSpec = new DataSpec(uri);
        final FileDataSource fileDataSource = new FileDataSource();
        try {
            fileDataSource.open(dataSpec);
        } catch (FileDataSource.FileDataSourceException e) {
            e.printStackTrace();
        }
    
        DataSource.Factory factory = new DataSource.Factory() {
            @Override
            public DataSource createDataSource() {
                return fileDataSource;
            }
        };
        CacheDataSourceFactory cacheDataSourceFactory = new CacheDataSourceFactory(cache, factory);
        MediaSource audioSource = new ExtractorMediaSource(fileDataSource.getUri(),
                cacheDataSourceFactory, new DefaultExtractorsFactory(), null, null);