SurfaceView与MediaPlayer搭配使用
实现音乐和歌词联动
package com.example.mp_class;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
import com.example.mp_class.bean.MySong;
import com.example.mp_class.bean.SongBean;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class SongActivity extends AppCompatActivity implements SurfaceHolder.Callback{
private static final String TAG = "123321";
private SurfaceView surfaceView;
private SurfaceHolder holder;
private Timer time=new Timer();
private MediaPlayer mp;
private int index;
private List<MySong> list=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_song);
surfaceView=findViewById(R.id.song_surface);
holder=surfaceView.getHolder();
holder.addCallback(this);
requestPermissions(new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE},111);
}
private void play_music() {
mp=new MediaPlayer();
try {
mp.setDataSource("/sdcard/txt/凤凰传奇 - 最炫民族风(Live).mp3");
mp.prepareAsync();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mp.start();
time.schedule(new TimerTask(