アンドロイドメディアプレーヤーの曲とシークバー

このチュートリアルでは、MediaPlayerクラスを使用してAndroidアプリケーション内に基本的なオーディオプレーヤーを実装します。プレイ/ストップ機能を追加し、ユーザーがシークバーを使用して曲の位置を変更することも可能にします。

Androidのメディアプレーヤー

メディアプレーヤークラスは、オーディオファイルやビデオファイルの再生に使用されます。使用するメディアプレーヤークラスの一般的なメソッドは以下の通りです。

  • start()
  • stop()
  • release() – To prevent memory leaks.
  • seekTo(position) – This will be used with the SeekBar
  • isPlaying() – Let’s us know whether the song is being played or not.
  • getDuration() – Is used to get the total duration. Using this we’ll know the upper limit of our SeekBar. This function returns the duration in milli seconds
  • setDataSource(FileDescriptor fd) – This is used to set the file to be played.
  • setVolume(float leftVolume, float rightVolume) – This is used to set the volume level. The value is a float between 0 an 1.

私たちはAndroid Studioのプロジェクトのアセットフォルダに保存されているmp3ファイルを再生します。アセットフォルダから音声アセットファイルを取得します。

AssetFileDescriptor descriptor = getAssets().openFd("filename");
                mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
                descriptor.close();

現在の曲の位置を変えることができるオーディオを再生するアプリケーションを作成するために、3つの要素を実装する必要があります。

  • MediaPlayer
  • SeekBar With Text – To show the current progress time besides the thumb.
  • Runnable Thread – To update the Seekbar.

プロジェクトの構成

次の依存関係をあなたのbuild.gradleに追加してください。

implementation 'com.android.support:design:28.0.0-alpha3'

コード

以下にactivity_main.xmlのコードが示されています。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center"
    android:layout_margin="16dp"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="PLAY/STOP SONG.\nSCRUB WITH SEEKBAR"
        android:textStyle="bold" />


    <SeekBar
        android:id="@+id/seekbar"
        android:layout_margin="16dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />


    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


    <android.support.design.widget.FloatingActionButton
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:src="@android:drawable/ic_media_play"
        android:text="PLAY SOUND" />

</LinearLayout>

クリックすると再生/停止するFloatingActionButtonを追加しました。MainActivity.javaクラスのコードは以下の通りです。

package com.scdev.androidmediaplayersong;

import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements Runnable {


    MediaPlayer mediaPlayer = new MediaPlayer();
    SeekBar seekBar;
    boolean wasPlaying = false;
    FloatingActionButton fab;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        fab = findViewById(R.id.button);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                playSong();
            }
        });

        final TextView seekBarHint = findViewById(R.id.textView);

        seekBar = findViewById(R.id.seekbar);

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

                seekBarHint.setVisibility(View.VISIBLE);
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
                seekBarHint.setVisibility(View.VISIBLE);
                int x = (int) Math.ceil(progress / 1000f);

                if (x  0 && mediaPlayer != null && !mediaPlayer.isPlaying()) {
                    clearMediaPlayer();
                    fab.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, android.R.drawable.ic_media_play));
                    MainActivity.this.seekBar.setProgress(0);
                }

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {


                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    mediaPlayer.seekTo(seekBar.getProgress());
                }
            }
        });
    }

    public void playSong() {

        try {


            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                clearMediaPlayer();
                seekBar.setProgress(0);
                wasPlaying = true;
                fab.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, android.R.drawable.ic_media_play));
            }


            if (!wasPlaying) {

                if (mediaPlayer == null) {
                    mediaPlayer = new MediaPlayer();
                }

                fab.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, android.R.drawable.ic_media_pause));

                AssetFileDescriptor descriptor = getAssets().openFd("suits.mp3");
                mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
                descriptor.close();

                mediaPlayer.prepare();
                mediaPlayer.setVolume(0.5f, 0.5f);
                mediaPlayer.setLooping(false);
                seekBar.setMax(mediaPlayer.getDuration());

                mediaPlayer.start();
                new Thread(this).start();

            }

            wasPlaying = false;
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    public void run() {

        int currentPosition = mediaPlayer.getCurrentPosition();
        int total = mediaPlayer.getDuration();


        while (mediaPlayer != null && mediaPlayer.isPlaying() && currentPosition < total) {
            try {
                Thread.sleep(1000);
                currentPosition = mediaPlayer.getCurrentPosition();
            } catch (InterruptedException e) {
                return;
            } catch (Exception e) {
                return;
            }

            seekBar.setProgress(currentPosition);

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        clearMediaPlayer();
    }

    private void clearMediaPlayer() {
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
    }
}

上記のコードでは、FloatingActionButtonをクリックすると、playSong関数がトリガーされ、その中で曲が停止し、MediaPlayerとFloatingActionButtonのアイコンが毎秒別の時間でリセットされます。mediaPlayer.prepare()が呼び出されると、曲の詳細が利用可能になります。これにより、曲の所要時間を取得し、SeekBarの最大位置に設定することができます。setLoopingをfalseに設定することで、ユーザーによる停止まで曲を無限に再生することを防止します。runnableインタフェースで実装したrunメソッドをトリガーするスレッドを開始します。runメソッド内では、進行状況を毎秒更新し、SeekBarリスナーのonProgressChangedメソッドをトリガーします。リスナー内では、TextViewオフセットをSeekBarのスライダーの下に設定します。そこでミリ秒を秒に変換して時間の長さを設定します。SeekBarが移動されると、同じメソッドがトリガーされます。ユーザーがSeekBarの操作を停止すると、onStopTrackingTouchがトリガーされ、seekToメソッドを使用してMediaPlayerインスタンス上の曲の位置を更新します。曲が完了すると、SeekBarの位置を初期値に戻し、MediaPlayerインスタンスをクリアします。オーディオのないアプリケーションの出力は以下の通りです:このチュートリアルはこれで終了です。以下のリンクからプロジェクトをダウンロードし、自分で曲を再生してみてください。

アンドロイドメディアプレイヤーの曲

Githubプロジェクトのリンク

コメントを残す 0

Your email address will not be published. Required fields are marked *