📌  相关文章
📜  如何使用Firebase实时数据库在Android中创建动态视频播放器?

📅  最后修改于: 2021-05-10 16:49:31             🧑  作者: Mango

大多数应用程序都使用视频播放器在其应用程序中显示这么多视频。因此,对于播放视频,应用程序将从其视频URL播放视频。但是,如果我们想实时更新该视频怎么办。因此,在这种情况下,我们必须更新数据库,然后再更新APK。因此,这不是一种有效的方法。在本文中,我们将介绍使用Firebase Realtime Database在Android中实现动态视频播放器的方法。

我们将在本文中构建什么?

我们将构建一个简单的应用程序,在其中我们将在ExoPlayer中播放视频,并将从Firebase将视频加载到我们的ExoPlayer中。除此之外,我们将能够在运行时更改视频。下面提供了一个示例视频,以使您对我们在本文中将要做的事情有个大概的了解。注意,我们将使用Java语言实现该项目。

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

第2步:将您的应用连接到Firebase

创建新项目后。导航到顶部栏上的“工具”选项。在里面单击Firebase。单击Firebase后,您可以在屏幕快照中看到下面提到的右列。

在该列内,导航到Firebase实时数据库。单击该选项,您将在“将应用程序连接到Firebase”和“将Firebase实时数据库添加到您的应用程序”中看到两个选项。单击立即连接选项,您的应用程序将连接到Firebase。之后,单击第二个选项,现在您的应用已连接到Firebase。

完成此过程后,您将看到以下屏幕。

现在,验证您的应用是否已连接到Firebase。转到您的build.gradle文件。导航至应用程序> Gradle脚本> build.gradle(app)文件,并确保在依赖项部分中添加了以下依赖项。

添加此依赖关系后,在Gradle文件中添加ExoPlayer的依赖关系。

步骤3:在build.gradle文件中添加ExoPlayer View的依赖项

导航至应用程序> Gradle脚本> build.gradle(应用程序)文件,然后在其中添加以下依赖项。

添加此依赖项后,同步您的项目。现在,我们将转向XML部分。

步骤4:为Internet添加权限

当我们从Internet加载视频时,我们必须在Manifest文件中添加Internet权限。导航至应用程序> AndroidManifest.xml文件,然后在其中添加以下权限。

XML



XML


  
    
    
  


Java
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
  
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
  
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.extractor.ExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
  
public class MainActivity extends AppCompatActivity {
  
    // creating a variable for our Firebase Database.
    FirebaseDatabase firebaseDatabase;
      
    // creating a variable for our Database 
    // Reference for Firebase.
    DatabaseReference databaseReference;
      
    // creating a variable for exoplayerview.
    SimpleExoPlayerView exoPlayerView;
      
    // creating a variable for exoplayer
    SimpleExoPlayer exoPlayer;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        exoPlayerView = findViewById(R.id.idExoPlayerView);
          
        // below line is used to get the 
        // instance of our Firebase database.
        firebaseDatabase = FirebaseDatabase.getInstance();
          
        // below line is used to get reference for our database.
        databaseReference = firebaseDatabase.getReference("url");
        getVideoUrl();
    }
  
    private void getVideoUrl() {
        // calling add value event listener method 
        // for getting the values from database.
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                // this method is call to get the 
                // realtime updates in the data.
                // this method is called when the 
                // data is changed in our Firebase console.
                // below line is for getting the data 
                // from snapshot of our database.
                String videoUrl = snapshot.getValue(String.class);
                  
                // after getting the value for our video url 
                // we are passing that value to our
                // initialize exoplayer method to load our video
                initializeExoplayerView(videoUrl);
            }
  
            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                // calling on cancelled method when we receive
                // any error or we are not able to get the data.
                Toast.makeText(MainActivity.this, "Fail to get video url.", Toast.LENGTH_SHORT).show();
            }
        });
    }
  
    private void initializeExoplayerView(String videoURL) {
        try {
            // bandwidthmeter is used for getting default bandwidth
            BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
            // track selector is used to navigate between video using a default seeker.
            TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveTrackSelection.Factory(bandwidthMeter));
              
            // we are adding our track selector to exoplayer.
            exoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector);
             
            // we are parsing a video url and 
            // parsing its video uri.
            Uri videouri = Uri.parse(videoURL);
             
            // we are creating a variable for data source
            // factory and setting its user agent as 'exoplayer_view'
            DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory("exoplayer_video");
              
            // we are creating a variable for extractor 
            // factory and setting it to default extractor factory.
            ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
              
            // we are creating a media source with above variables 
            // and passing our event handler as null,
            MediaSource mediaSource = new ExtractorMediaSource(videouri, dataSourceFactory, extractorsFactory, null, null);
              
            // inside our exoplayer view 
            // we are setting our player
            exoPlayerView.setPlayer(exoPlayer);
              
            // we are preparing our exoplayer 
            // with media source.
            exoPlayer.prepare(mediaSource);
              
            // we are setting our exoplayer 
            // when it is ready.
            exoPlayer.setPlayWhenReady(true);
        } catch (Exception e) {
            // below line is used for handling our errors.
            Log.e("TAG", "Error : " + e.toString());
        }
    }
}


步骤5:使用activity_main.xml文件

转到activity_main.xml文件,并参考以下代码。以下是activity_main.xml文件的代码

XML格式



  
    
    
  

步骤6:使用MainActivity。 Java文件

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
  
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
  
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.extractor.ExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
  
public class MainActivity extends AppCompatActivity {
  
    // creating a variable for our Firebase Database.
    FirebaseDatabase firebaseDatabase;
      
    // creating a variable for our Database 
    // Reference for Firebase.
    DatabaseReference databaseReference;
      
    // creating a variable for exoplayerview.
    SimpleExoPlayerView exoPlayerView;
      
    // creating a variable for exoplayer
    SimpleExoPlayer exoPlayer;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        exoPlayerView = findViewById(R.id.idExoPlayerView);
          
        // below line is used to get the 
        // instance of our Firebase database.
        firebaseDatabase = FirebaseDatabase.getInstance();
          
        // below line is used to get reference for our database.
        databaseReference = firebaseDatabase.getReference("url");
        getVideoUrl();
    }
  
    private void getVideoUrl() {
        // calling add value event listener method 
        // for getting the values from database.
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                // this method is call to get the 
                // realtime updates in the data.
                // this method is called when the 
                // data is changed in our Firebase console.
                // below line is for getting the data 
                // from snapshot of our database.
                String videoUrl = snapshot.getValue(String.class);
                  
                // after getting the value for our video url 
                // we are passing that value to our
                // initialize exoplayer method to load our video
                initializeExoplayerView(videoUrl);
            }
  
            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                // calling on cancelled method when we receive
                // any error or we are not able to get the data.
                Toast.makeText(MainActivity.this, "Fail to get video url.", Toast.LENGTH_SHORT).show();
            }
        });
    }
  
    private void initializeExoplayerView(String videoURL) {
        try {
            // bandwidthmeter is used for getting default bandwidth
            BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
            // track selector is used to navigate between video using a default seeker.
            TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveTrackSelection.Factory(bandwidthMeter));
              
            // we are adding our track selector to exoplayer.
            exoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector);
             
            // we are parsing a video url and 
            // parsing its video uri.
            Uri videouri = Uri.parse(videoURL);
             
            // we are creating a variable for data source
            // factory and setting its user agent as 'exoplayer_view'
            DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory("exoplayer_video");
              
            // we are creating a variable for extractor 
            // factory and setting it to default extractor factory.
            ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
              
            // we are creating a media source with above variables 
            // and passing our event handler as null,
            MediaSource mediaSource = new ExtractorMediaSource(videouri, dataSourceFactory, extractorsFactory, null, null);
              
            // inside our exoplayer view 
            // we are setting our player
            exoPlayerView.setPlayer(exoPlayer);
              
            // we are preparing our exoplayer 
            // with media source.
            exoPlayer.prepare(mediaSource);
              
            // we are setting our exoplayer 
            // when it is ready.
            exoPlayer.setPlayWhenReady(true);
        } catch (Exception e) {
            // below line is used for handling our errors.
            Log.e("TAG", "Error : " + e.toString());
        }
    }
}

第7步:在Firebase控制台中添加视频的URL

用于在Firebase控制台中添加视频URL。在浏览器中浏览Firebase,然后单击右上角的“转到控制台”选项,如以下屏幕截图所示。

单击“转到控制台”选项后,您将看到您的项目。从可用的项目列表中单击您的项目名称。

单击项目后。单击左侧窗口中的实时数据库选项。

单击此选项后,您将看到右侧的屏幕。在此页面上,单击顶部栏中的“规则”选项。您将看到以下屏幕。

在此项目中,我们添加了适用于读取和写入的规则,因为我们没有使用任何身份验证来验证用户。因此,我们目前将其设置为true以测试我们的应用程序。更改规则后。单击右上角的“发布”按钮,您的规则将保存在此处。现在再次回到“数据”选项卡。现在,我们将从Firebase本身将数据手动添加到Firebase。

在Firebase实时数据库中。导航到“数据”选项卡。在数据库部分的此选项卡内,单击“ +”图标。单击“ +”图标后,您将看到两个输入字段,即“名称”和“值”字段。在“名称”字段中,您必须添加视频文件的引用,在本例中为“ url ”。在值字段中,我们必须添加视频文件的URL。在此字段中添加值之后。单击添加按钮,您的数据将被添加到Firebase控制台。

添加视频的网址后。现在运行您的应用程序,并在下面查看该应用程序的输出:

输出:

您可以动态更改视频的URL。

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!