Tocar áudio e vídeo no android com Java
Android Java

Tocar áudio e vídeo no android com Java





Nesse tutorial vou descrever como fazer para tocar áudio e vídeo no android com Java num aplicativo bem simples para ver como funciona o MediaPlayer.

Copiando arquivos para as pastas

Primeiramente neste aplicativo vamos criar a pasta raw dentro da pasta res para poder copiar e colar um vídeo e uma música.

Ficando da seguinte maneira.

Tocar áudio e vídeo no android com Java
Pasta raw dentro do res

Logo depois de ter criado a pasta raw você deve copiar e colar um arquivo de música(mp3) e um vídeo(mp4) dentro da pasta como na imagem a seguir.

Tocar áudio e vídeo no android com Java
music.mp3 e video.mp4

Então chegou a hora de copiar uma imagem para dentro da pasta drawable e criar 4 Vector Aset de sua preferência para utilizar no projeto com os seguintes nomes.

Arquivos de imagem
Arquivos de imagem

Logo após ter criado a pasta raw e copiado todos os arquivos chegou a hora de programar.





Programando o aplicativo

Vamos então criar alguns arquivos de layout com os seguintes nomes e conteúdo.

audio.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <androidx.appcompat.widget.AppCompatSeekBar
        android:id="@+id/seekVolume"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:rotation="270"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginEnd="250dp" />
    <SeekBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <TextView
        android:id="@+id/tvTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pause"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@id/progressBar"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />
    <LinearLayout
        android:id="@+id/layButtons"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:gravity="center"
        app:layout_constraintTop_toBottomOf="@id/progressBar">
        <ImageButton
            android:id="@+id/btnPlay"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_play" />
        <ImageButton
            android:id="@+id/btnPause"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_pause" />
        <ImageButton
            android:id="@+id/btnStop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_stop" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>




base.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">
    <Button
        android:id="@+id/btnAudio"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Audio"/>
    <Button
        android:id="@+id/btnImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Image"/>
    <Button
        android:id="@+id/btnVideo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Video"/>
</LinearLayout>

image.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/logo_new"/>
</androidx.constraintlayout.widget.ConstraintLayout>

video.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:contextClickable="true">
    <VideoView
        android:id="@+id/videoView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

Logo depois vamos deixar nossa activity_main.xml da seguinte maneira.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:layout_weight="3">
            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:src="@drawable/ic_android"
                android:padding="16dp"
                android:layout_weight="1"/>
            <TextView
                android:id="@+id/txTitle"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Escolha a opção"
                android:textColor="#000"
                android:textSize="20sp"
                android:textStyle="bold"
                android:gravity="center"
                android:layout_weight="1"/>
        </LinearLayout>
        <ViewFlipper
            android:id="@+id/vf"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1">
                <include layout="@layout/base"/>
                <include layout="@layout/audio"/>
                <include layout="@layout/image"/>
                <include layout="@layout/video"/>
        </ViewFlipper>
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>




Então agora vamos colocar tudo em prática deixando nossa MainActivity com o seguinte código para executar as funções do aplicativo.

package br.com.uware.taiv;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.MediaController;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;
import android.widget.ViewFlipper;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    private MediaPlayer mediaPlayer;
    private SeekBar seekVolume;
    private AudioManager audioManager;
    private SeekBar progressBar;
    private TextView tvTime;
    private ViewFlipper vf;
    private TextView txTitle;
    ImageButton btnPlay, btnPause, btnStop;
    private VideoView videoView;

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

        Button btnAudio = findViewById(R.id.btnAudio);
        Button btnImage = findViewById(R.id.btnImage);
        Button btnVideo = findViewById(R.id.btnVideo);
        txTitle = findViewById(R.id.txTitle);
        vf = findViewById(R.id.vf);
        btnPlay = findViewById(R.id.btnPlay);
        btnPause =findViewById(R.id.btnPause);
        btnStop = findViewById(R.id.btnStop);
        progressBar = findViewById(R.id.progressBar);
        tvTime = findViewById(R.id.tvTime);

        initSeekBar();
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int volMax = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int volNow = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        seekVolume.setMax(volMax);
        seekVolume.setProgress(volNow);
        mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.music);
        videoView = findViewById(R.id.videoView);
        videoView.setMediaController(new MediaController(this));

        btnAudio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkPlay();
                txTitle.setText("Audio");
                vf.setDisplayedChild(1);
            }
        });
        btnImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkPlay();
                txTitle.setText("Image");
                vf.setDisplayedChild(2);
            }
        });
        btnVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkPlay();
                txTitle.setText("Video");
                vf.setDisplayedChild(3);
                videoView.setVideoPath("android.resource://" + getPackageName() + "/" + R.raw.video);
            }
        });

        btnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                playSong();
            }
        });
        btnPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pauseSong();
            }
        });
        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stopSong();
            }
        });
        seekVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, AudioManager.FLAG_SHOW_UI);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if(b){
                    mediaPlayer.seekTo(i);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

    }

    private void initSeekBar(){
        seekVolume = findViewById(R.id.seekVolume);
    }
    private Handler handler = new Handler();
    private Runnable update;
    public void  play(){
        progressBar.setMax(mediaPlayer.getDuration());
        update = new Runnable() {
            @Override
            public void run(){
                SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
                Date d = new Date(mediaPlayer.getCurrentPosition());
                tvTime.setText(sdf.format(d));
                progressBar.setProgress(mediaPlayer.getCurrentPosition());
                handler.postDelayed( this, 1000);
            }
        };
        handler.postDelayed(update,100);
    }
    public void playSong(){
        if(mediaPlayer != null) {
            mediaPlayer.start();
            play();
        }
        else{
            mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.music);
            play();
        }
    }
    public void pauseSong(){
        if(mediaPlayer.isPlaying()){
            mediaPlayer.pause();
        }
    }
    public void stopSong(){
        mediaPlayer.stop();
        mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.music);
    }
    public void checkPlay(){
        if (mediaPlayer.isPlaying()) {
            stopSong();
        }
        if(videoView.isPlaying()){
            videoView.stopPlayback();
        }
    }
    @Override
    public void onBackPressed() {
        checkPlay();
        vf.setDisplayedChild(0);
    }
}

Enfim espero poder ter ajudado nesse tutorial sobre tocar áudio e vídeo no android com Java e que você tenha entendido como funciona a biblioteca do MediaPlayer e suas funções com threads.

Veja também:





Rodrigo Leutz
Desenvolvedor Web e Android ( Kotlin e Java )
http://www.test.com/