📜  Android-MediaPlayer

📅  最后修改于: 2021-01-05 05:22:38             🧑  作者: Mango


Android提供了许多方法来控制音频/视频文件和流的播放。一种方法是通过称为MediaPlayer的类。

Android提供了MediaPlayer类来访问内置的媒体播放器服务,例如播放音频,视频等。为了使用MediaPlayer,我们必须调用此类的静态方法create() 。此方法返回MediaPlayer类的实例。它的语法如下-

MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);

第二个参数是您要播放的歌曲的名称。您必须在项目下创建一个名为raw的新文件夹,并将音乐文件放入其中。

创建Mediaplayer对象后,您可以调用一些方法来启动或停止音乐。这些方法在下面列出。

mediaPlayer.start();
mediaPlayer.pause();

在调用start()方法时,音乐将从头开始播放。如果在pause()方法之后再次调用此方法,则音乐将从左端开始播放,而不是从头开始。

为了从头开始播放音乐,您必须调用reset()方法。其语法如下。

mediaPlayer.reset();

除了start和pause方法之外,此类还提供了其他方法来更好地处理音频/视频文件。这些方法在下面列出-

Sr.No Method & description
1

isPlaying()

This method just returns true/false indicating the song is playing or not

2

seekTo(position)

This method takes an integer, and move song to that particular position millisecond

3

getCurrentPosition()

This method returns the current position of song in milliseconds

4

getDuration()

This method returns the total time duration of song in milliseconds

5

reset()

This method resets the media player

6

release()

This method releases any resource attached with MediaPlayer object

7

setVolume(float leftVolume, float rightVolume)

This method sets the up down volume for this player

8

setDataSource(FileDescriptor fd)

This method sets the data source of audio/video file

9

selectTrack(int index)

This method takes an integer, and select the track from the list on that particular index

10

getTrackInfo()

This method returns an array of track information

这是一个演示MediaPlayer类用法的示例。它创建了一个基本的媒体播放器,可让您前进,后退,播放和暂停歌曲。

要试验此示例,您需要在实际设备上运行此示例以听到音频声音。

Steps Description
1 You will use Android studio IDE to create an Android application under a package com.example.sairamkrishna.myapplication.
2 Modify src/MainActivity.java file to add MediaPlayer code.
3 Modify the res/layout/activity_main to add respective XML components
4 Create a new folder under MediaPlayer with name as raw and place an mp3 music file in it with name as song.mp3
5 Run the application and choose a running android device and install the application on it and verify the results

以下是修改后的主要活动文件src / MainActivity.java的内容

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.TimeUnit;


public class MainActivity extends Activity {
   private Button b1,b2,b3,b4;
   private ImageView iv;
   private MediaPlayer mediaPlayer;
    
   private double startTime = 0;
   private double finalTime = 0;
    
   private Handler myHandler = new Handler();;
   private int forwardTime = 5000;
   private int backwardTime = 5000;
   private SeekBar seekbar;
   private TextView tx1,tx2,tx3;

   public static int oneTimeOnly = 0;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      b1 = (Button) findViewById(R.id.button);
      b2 = (Button) findViewById(R.id.button2);
      b3 = (Button)findViewById(R.id.button3);
      b4 = (Button)findViewById(R.id.button4);
      iv = (ImageView)findViewById(R.id.imageView);

      tx1 = (TextView)findViewById(R.id.textView2);
      tx2 = (TextView)findViewById(R.id.textView3);
      tx3 = (TextView)findViewById(R.id.textView4);
      tx3.setText("Song.mp3");

      mediaPlayer = MediaPlayer.create(this, R.raw.song);
      seekbar = (SeekBar)findViewById(R.id.seekBar);
      seekbar.setClickable(false);
      b2.setEnabled(false);

      b3.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Playing 
               sound",Toast.LENGTH_SHORT).show();
            mediaPlayer.start();

            finalTime = mediaPlayer.getDuration();
            startTime = mediaPlayer.getCurrentPosition();

            if (oneTimeOnly == 0) {
               seekbar.setMax((int) finalTime);
               oneTimeOnly = 1;
            }
                
            tx2.setText(String.format("%d min, %d sec",
               TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
               TimeUnit.MILLISECONDS.toSeconds((long) finalTime) -
               TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) 
                  finalTime)))
            );

            tx1.setText(String.format("%d min, %d sec",
               TimeUnit.MILLISECONDS.toMinutes((long) startTime),
               TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
               TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) 
                  startTime)))
            );

            seekbar.setProgress((int)startTime);
            myHandler.postDelayed(UpdateSongTime,100);
            b2.setEnabled(true);
            b3.setEnabled(false);
         }
      });

      b2.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Pausing 
               sound",Toast.LENGTH_SHORT).show();
            mediaPlayer.pause();
            b2.setEnabled(false);
            b3.setEnabled(true);
         }
      });

      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            int temp = (int)startTime;

            if((temp+forwardTime)<=finalTime){
               startTime = startTime + forwardTime;
               mediaPlayer.seekTo((int) startTime);
               Toast.makeText(getApplicationContext(),"You have Jumped forward 5 
                  seconds",Toast.LENGTH_SHORT).show();
            }else{
               Toast.makeText(getApplicationContext(),"Cannot jump forward 5
                  seconds",Toast.LENGTH_SHORT).show();
            }
         }
      });

      b4.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            int temp = (int)startTime;

            if((temp-backwardTime)>0){
               startTime = startTime - backwardTime;
               mediaPlayer.seekTo((int) startTime);
               Toast.makeText(getApplicationContext(),"You have Jumped backward 5 
                  seconds",Toast.LENGTH_SHORT).show();
            }else{
               Toast.makeText(getApplicationContext(),"Cannot jump backward 5 
                  seconds",Toast.LENGTH_SHORT).show();
            }
         }
      });
   }

   private Runnable UpdateSongTime = new Runnable() {
      public void run() {
         startTime = mediaPlayer.getCurrentPosition();
         tx1.setText(String.format("%d min, %d sec",
            TimeUnit.MILLISECONDS.toMinutes((long) startTime),
            TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
            toMinutes((long) startTime)))
         );
         seekbar.setProgress((int)startTime);
         myHandler.postDelayed(this, 100);
      }
   };
}

以下是xml res / layout / activity_main.xml的修改内容。

在下面的代码中abc表示tutorialspoint.com的徽标




   

   

   

   

   

   

   

   

   

   

   


以下是res / values /字符串.xml的内容


   My Application
   
   
   >]]>
   ||

以下是AndroidManifest.xml文件的内容。




   
      
      
         
         
            
            
         
         
      
      
   

让我们尝试运行您的应用程序。我假设您已将实际的Android Mobile设备与计算机连接。要从Eclipse运行该应用程序,请打开项目的活动文件之一,然后单击“运行”。Eclipse运行图标工具栏中的图标。在启动您的应用程序之前,Android Studio将显示以下屏幕

Anroid MediaPlayer教程

默认情况下,您会看到暂停按钮处于禁用状态。现在按播放按钮,它将变为禁用,暂停按钮将变为启用。如下图所示-

到目前为止,音乐一直在播放。现在按暂停按钮,然后查看暂停通知。这如下所示-

Anroid MediaPlayer教程

现在,当您再次按下播放按钮时,歌曲将不会从头开始播放,而是从暂停位置播放。现在,按快进或快退按钮可将歌曲快进或快退5秒钟。歌曲无法向前跳的时候到了。在这一点上,将出现这样的通知-

Anroid MediaPlayer教程

当您在手机上执行其他任务时,音乐将继续在后台播放。为了停止它,您必须从后台活动中退出此应用程序。

Anroid MediaPlayer教程

上图显示了当您选择快退按钮时。