웹사이트 검색

SeekBar가 포함된 Android 미디어 플레이어 노래


이 자습서에서는 MediaPlayer 클래스를 사용하여 Android 애플리케이션에서 기본 오디오 플레이어를 구현합니다. 재생/정지 기능을 추가하고 사용자가 SeekBar로 노래의 위치를 변경할 수 있도록 할 것입니다.

안드로이드 미디어 플레이어

MediaPlayer 클래스는 오디오 및 비디오 파일을 재생하는 데 사용됩니다. 우리가 사용할 MediaPlayer 클래스의 일반적인 메서드는 다음과 같습니다.

  • 시작()
  • 중지()
  • release() - 메모리 누수를 방지합니다.
  • seekTo(position) - SeekBar와 함께 사용됩니다
  • isPlaying() - 노래가 재생되고 있는지 알려주세요.
  • getDuration() - 총 기간을 가져오는 데 사용됩니다. 이를 사용하여 SeekBar의 상한선을 알 수 있습니다. 이 함수는 기간을 밀리초 단위로 반환합니다.
  • setDataSource(FileDescriptor fd) - 재생할 파일을 설정하는 데 사용됩니다.
  • setVolume(float leftVolume, float rightVolume) - 볼륨 레벨을 설정하는 데 사용됩니다. 값은 0과 1 사이의 실수입니다.

Android Studio 프로젝트의 자산 폴더에 저장된 mp3 파일을 재생합니다. Assets 폴더에서 사운드 자산 파일 가져오기

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

오디오를 재생하고 현재 노래 트랙의 위치를 변경할 수 있는 애플리케이션을 생성하려면 다음 세 가지를 구현해야 합니다.

  • 미디어 플레이어
  • 텍스트가 있는 SeekBar - 엄지손가락 외에 현재 진행 시간을 표시합니다.
  • 실행 가능한 스레드 - Seekbar를 업데이트합니다.

프로젝트 구조

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>

클릭하면 재생/중지되는 FloatingActionButon을 추가했습니다. MainActivity.java 클래스의 코드는 다음과 같습니다.

package com.journaldev.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;
    }
}

AndroidMediaPlayerSong

Github 프로젝트 링크