Android-mediaplayer

提供:Dev Guides
移動先:案内検索

Android-MediaPlayer

Androidは、オーディオ/ビデオファイルとストリームの再生を制御する多くの方法を提供します。 この方法の1つは、 MediaPlayer というクラスを使用することです。

Androidは、MediaPlayerクラスを提供して、オーディオ、ビデオなどの組み込みのメディアプレーヤーサービスにアクセスします。 MediaPlayerを使用するには、このクラスの静的メソッド* create()*を呼び出す必要があります。 このメソッドは、MediaPlayerクラスのインスタンスを返します。 その構文は次のとおりです-

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

2番目のパラメーターは、再生する曲の名前です。 プロジェクトの下に raw という名前の新しいフォルダを作成し、そこに音楽ファイルを配置する必要があります。

Mediaplayerオブジェクトを作成したら、いくつかのメソッドを呼び出して音楽を開始または停止できます。 これらのメソッドを以下にリストします。

mediaPlayer.start();
mediaPlayer.pause();
  • start()*メソッドを呼び出すと、音楽は最初から再生を開始します。 * pause()*メソッドの後にこのメソッドが再度呼び出されると、音楽は最初からではなく、残っているところから再生が開始されます。

音楽を最初から開始するには、* reset()*メソッドを呼び出す必要があります。 その構文は次のとおりです。

mediaPlayer.reset();

startおよびpauseメソッドの他に、オーディオ/ビデオファイルをより適切に処理するために、このクラスによって提供される他のメソッドがあります。 これらの方法は以下のとおりです-

Sr.No Method & description
1

isPlaying()

このメソッドは、曲が再生されているかどうかを示すtrue/falseを返すだけです

2

seekTo(position)

このメソッドは整数を取り、その特定の位置に曲をミリ秒移動します

3

getCurrentPosition()

このメソッドは、曲の現在の位置をミリ秒単位で返します

4

getDuration()

このメソッドは、曲の合計時間をミリ秒単位で返します

5

reset()

このメソッドは、メディアプレーヤーをリセットします

6

release()

このメソッドは、MediaPlayerオブジェクトに関連付けられたリソースを解放します

7

setVolume(float leftVolume, float rightVolume)

このメソッドは、このプレーヤーの音量を設定します

8

setDataSource(FileDescriptor fd)

このメソッドは、オーディオ/ビデオファイルのデータソースを設定します

9

selectTrack(int index)

このメソッドは整数を取り、その特定のインデックスのリストからトラックを選択します

10

getTrackInfo()

このメソッドは、トラック情報の配列を返します

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 *はfinddevguides.comのロゴを示します_

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

   <TextView android:text="Music Palyer" android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textview"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"/>

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#ff7aff24"
      android:textSize="35dp"/>

   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:src="@drawable/abc"/>

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/forward"
      android:id="@+id/button"
      android:layout_alignParentBottom="true"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"/>

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/pause"
      android:id="@+id/button2"
      android:layout_alignParentBottom="true"
      android:layout_alignLeft="@+id/imageView"
      android:layout_alignStart="@+id/imageView"/>

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/back"
      android:id="@+id/button3"
      android:layout_alignTop="@+id/button2"
      android:layout_toRightOf="@+id/button2"
      android:layout_toEndOf="@+id/button2"/>

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/rewind"
      android:id="@+id/button4"
      android:layout_alignTop="@+id/button3"
      android:layout_toRightOf="@+id/button3"
      android:layout_toEndOf="@+id/button3"/>

   <SeekBar
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/seekBar"
      android:layout_alignLeft="@+id/textview"
      android:layout_alignStart="@+id/textview"
      android:layout_alignRight="@+id/textview"
      android:layout_alignEnd="@+id/textview"
      android:layout_above="@+id/button"/>

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textAppearance="?android:attr/textAppearanceSmall"
      android:text="Small Text"
      android:id="@+id/textView2"
      android:layout_above="@+id/seekBar"
      android:layout_toLeftOf="@+id/textView"
      android:layout_toStartOf="@+id/textView"/>

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textAppearance="?android:attr/textAppearanceSmall"
      android:text="Small Text"
      android:id="@+id/textView3"
      android:layout_above="@+id/seekBar"
      android:layout_alignRight="@+id/button4"
      android:layout_alignEnd="@+id/button4"/>

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textAppearance="?android:attr/textAppearanceMedium"
      android:text="Medium Text"
      android:id="@+id/textView4"
      android:layout_alignBaseline="@+id/textView2"
      android:layout_alignBottom="@+id/textView2"
      android:layout_centerHorizontal="true"/>

</RelativeLayout>

以下は res/values/string.xml の内容です。

<resources>
   <string name="app_name">My Application</string>
   <string name="back"><![CDATA[<]]></string>
   <string name="rewind"><![CDATA[<<]]></string>
   <string name="forward"><![CDATA[>>]]></string>
   <string name="pause">||</string>
</resources>

以下は AndroidManifest.xml ファイルの内容です。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >

      <activity
         android:name="com.example.sairamkrishna.myapplication.MainActivity"
         android:label="@string/app_name" >

         <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
         </intent-filter>

      </activity>

   </application>
</manifest>

アプリケーションを実行してみましょう。 実際のAndroidモバイルデバイスをコンピューターに接続していると思います。 Eclipseからアプリを実行するには、プロジェクトのアクティビティファイルの1つを開き、ツールバーの[Eclipse Run Iconアイコンの実行]をクリックします。 アプリケーションを開始する前に、Androidスタジオには次の画面が表示されます

Android MediaPlayerチュートリアル

デフォルトでは、一時停止ボタンは無効になっています。 再生ボタンを押すと、無効になり、一時停止ボタンが有効になります。 それは下の写真に示されています-

これまで、音楽は再生されてきました。 一時停止ボタンを押して、一時停止通知を確認します。 これは以下に示されています-

Android MediaPlayerチュートリアル

もう一度再生ボタンを押すと、曲は最初からではなく、一時停止した場所から再生されます。 早送りまたは早戻しボタンを押して、曲を前後に5秒間ジャンプします。 歌を前に進めない時が来ました。 この時点で、このようなものになる通知が表示されます-

Android MediaPlayerチュートリアル

モバイルで他のタスクを実行している間、音楽はバックグラウンドで再生され続けます。 停止するには、このアプリケーションをバックグラウンドアクティビティから終了する必要があります。

Android MediaPlayerチュートリアル

上の画像は、巻き戻しボタンを選択したときを示しています。