Audio file playback in Android

Last time we talked about how to record an audio file. This time we will talk about how to play an audio file. Record audio, generally we will use it when sending voices in chat or uploading voices. Since recording is required, it must have a playback function. At the same time, we play audio, and music also needs to play. So today I will talk about the audio playback function.

1. Introduction to Media Player MediaPlayer

Since it is playing audio, then MediaPlayer is used. MediaPlayer is the audio and video player that comes with Android. It can be used to play media files recorded by MediaRecorder, including amr, aac, mp4, 3gp, as well as audio files such as mp3, wav, mid, ogg, and mkv, mov, avi, etc. Video files.

2. Common methods of MediaPlayer (common for broadcast and projection)

  • reset: Reset the player.
  • prepare: ready to play.
  • start: start playing
  • pause: Pause playback.
  • stop: Stop playing.
  • setOnPreparedListener: Set the listener to be played. Need to implement the onPrepared method of the interface MediaPlayer.OnPreparedListener.
  • setOnCompletionListener: Set the end playback listener. Need to implement the onCompletion method of the interface MediaPlayer.OnCompletionListener.
  • setOnSeekCompleteListener: Set the playback drag listener. Need to implement the onSeekComplete method of the interface MediaPlayer.OnSeekCompleteListener.
  • create: Create a player with the specified Uri.
  • setDataSource: Set the file path of the playback data source. Only one of the two methods of create and setDataSource needs to be called.
  • setVolume: Set the volume. The two parameters are the volume of the left channel and the right channel, with a value between 0 and 1.
  • setAudioStreamType: Set the type of audio stream. See Table 1 for the value description of the audio stream type.
Table 1

Ring type of AudioManager class

Ringtone name Description
STREAM_VOICE_CALL Call tone  
STREAM_SYSTEM System tone  
STREAM_RING Ring tone Ring tones for incoming calls and text messages
STREAM_MUSIC Media sound Audio, video, game, etc. sound
STREAM_ALARM Alarm tone  
STREAM_NOTIFICATION Notification tone  
  • setLooping: Set whether to loop playback. true means to play in a loop, false means to play only once.
  • isPlaying: Determine whether it is playing.
  • seekTo: Drag the playback progress to the specified position. This method can be used in conjunction with the SeekBar drag bar.
  • getCurrentPosition: Get the position of the current playback progress.
  • getDuration: Get the playback duration, in milliseconds.

3. Sample code

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ProgressBar
            android:id="@+id/pro_bar"
            style="@style/Widget.AppCompat.ProgressBar.Horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/bt_start"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="开始" />

        <Button
            android:id="@+id/bt_pause"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="暂停" />
    </LinearLayout>
</RelativeLayout>

MainActivity.java

public class MainActivity extends WaterPermissionActivity implements View.OnClickListener, MediaPlayer.OnCompletionListener {

    private String voicePath;
    private ProgressBar pro_bar;
    private Button bt_start;
    private Button bt_pause;
    private MediaPlayer mMediaPlayer;
    private Handler mHandler;
    private boolean isComplete = true;//是否完成

    @Override
    protected MvcBaseModel getModelImp() {
        return null;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initWidget() {
        pro_bar = findViewById(R.id.pro_bar);
        bt_start = findViewById(R.id.bt_start);
        bt_pause = findViewById(R.id.bt_pause);
        bt_start.setOnClickListener(this);
        bt_pause.setOnClickListener(this);
        requestPermission(WRITE_EXTERNAL_STORAGE);
    }

    @Override
    protected void doSDWrite() {
        requestPermission(READ_EXTERNAL_STORAGE);
    }

    @Override
    protected void doSDRead() {
        //初始化音源路径
        getPath();
        //初始化媒体播放器
        init();
    }

    /**
     * 录制前创建一个空文件并获取路径
     */
    private void getPath() {
        List<String> list = new ArrayList<>();
        list.add("record");
        String dirPath = PathGetUtil.getLongwayPath(this, list);
        File fileVoice = new File(dirPath, "voice1616667408548.amr");
        voicePath = fileVoice.getPath();
    }

    /**
     * 初始化MediaPlayer
     */
    private void init() {
        mHandler = new Handler();
        mMediaPlayer = new MediaPlayer();//创建一个媒体播放器
        mMediaPlayer.setOnCompletionListener(this);//设置媒体播放器的播放完成监听器
        //定时器
        mHandler.postDelayed(r, 100);//延时100毫秒
    }

    /**
     * 播放音频
     */
    private void play() {
        try {
            isComplete = false;
            //重置媒体播放器
            mMediaPlayer.reset();
            //设置音频类型为音乐
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            //设置媒体数据的文件路径
            mMediaPlayer.setDataSource(voicePath);
            //媒体播放器准备就绪
            mMediaPlayer.prepare();
            //媒体播放器开始播放
            mMediaPlayer.start();
            //设置进度条
            pro_bar.setMax(mMediaPlayer.getDuration());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_start:
                if (pro_bar.getProgress()!=0) {
                    //暂停开始
                    mMediaPlayer.start();
                } else {
                    //普通开始
                    play();
                }
                break;
            case R.id.bt_pause:
                if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.pause();
                }
                break;
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        isComplete = true;
        ToastUtil.toastWord(this, "播放完成");
    }

    private Runnable r = new Runnable() {
        @Override
        public void run() {
            if (mHandler != null) {
                if (isComplete) {
                    pro_bar.setProgress(0);
                } else {
                    pro_bar.setProgress(mMediaPlayer.getCurrentPosition());
                }
                mHandler.postDelayed(this, 500);
            }
        }
    };
}

 

Guess you like

Origin blog.csdn.net/weixin_38322371/article/details/115234871