使用Android Media Player播放音频文件

时间:2018-11-29 07:18:33

标签: android audio android-mediaplayer

在我的应用中,我正在使用媒体播放器播放单个音频文件(12 mb)。该应用程序包含三个活动ManiActivity,MWlyrics和About。 音频正在MainActivity中播放,问题是当我在这些活动之间切换时。音频停止播放。

 public class MainActivity extends AppCompatActivity {
        private MediaPlayer mp;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mp = MediaPlayer.create(this, R.raw.abc);
            getSupportActionBar().setElevation(0);
            ImageView imageView = (ImageView)findViewById(R.id.main_img_lm);
            Glide.with(this).load(R.drawable.lm)
                    .thumbnail(0.5f)
                    .into(imageView);




            }




            //play song method

        public void playSong (View v){
            mp.start();

        }

          //pause song method

        public void pauseSong (View v){
            mp.pause();
        }


          //stop song method

        public void stopSong (View v){
            mp.stop();
            mp = MediaPlayer.create(this, R.raw.abc);

            }

          // main menu
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.menur, menu);

            menu.add(0, 1, 1, menuIconWithText(getResources().getDrawable(R.drawable.ic_rate), getResources().getString(R.string.rate_us)));
            menu.add(0, 2, 2, menuIconWithText(getResources().getDrawable(R.drawable.ic_apps), getResources().getString(R.string.more_apps)));
            menu.add(0, 3, 3, menuIconWithText(getResources().getDrawable(R.drawable.ic_share), getResources().getString(R.string.share_app)));
            menu.add(0, 4, 4, menuIconWithText(getResources().getDrawable(R.drawable.ic_info), getResources().getString(R.string.about)));
            menu.add(0, 5, 5, menuIconWithText(getResources().getDrawable(R.drawable.ic_exit), getResources().getString(R.string.exit)));
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {


            switch (item.getItemId()) {

                    case 1:
                        Toast.makeText(MainActivity.this, "redirecting to rate us and review page page", Toast.LENGTH_SHORT).show();
                    return true;

                    case 2:
                        Toast.makeText(MainActivity.this, "thank you for using", Toast.LENGTH_SHORT).show();
                    return true;

                    case 3:
                        Toast.makeText(MainActivity.this, "sharing app..", Toast.LENGTH_SHORT).show();
                    return true;

                    case 4:
                        Toast.makeText(MainActivity.this, "about this app", Toast.LENGTH_SHORT).show();
                        Intent j = new Intent(this,About.class);
                        startActivity(j);
                        return true;

                    case 5:
                       finish();
                       mp.release();
                       return true;

                    case R.id.mdwtid:
                    Intent i = new Intent(this,MWLyrics.class);
                    startActivity(i);
                    return true;


            }

            return super.onOptionsItemSelected(item);
        }




        private CharSequence menuIconWithText(Drawable r, String title) {

            r.setBounds(0, 0, r.getIntrinsicWidth(), r.getIntrinsicHeight());
            SpannableString sb = new SpannableString("    " + title);
            ImageSpan imageSpan = new ImageSpan(r, ImageSpan.ALIGN_BOTTOM);
            sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            return sb;
        }
    }

应用程序详细信息..

MainActiviy-显示专辑图像和[播放,暂停和停止]图像。

Mwlyrics-显示歌曲歌词。

关于-显示应用信息。

如何解决此问题。

  
      
  1. 如何在其他活动之间切换时继续播放音频而不会受到任何干扰。

  2.   
  3. 如何在应用程序中有效使用此音频文件..考虑到内存。

  4.   

当在我的移动设备上测试应用程序(moto one power,android pie)时,我注意到频率(有时运行40%)和最大使用量为170 mb。这到底是什么意思。我是android开发的新手,我需要一些建议。

2 个答案:

答案 0 :(得分:1)

您需要为此使用服务。您可以检查以下代码

class BackgroundAudioService extends Service implements OnCompletionListener {
  MediaPlayer mediaPlayer;

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  @Override
  public void onCreate() {
    mediaPlayer = MediaPlayer.create(this, R.raw.s);// raw/s.mp3
    mediaPlayer.setOnCompletionListener(this);
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    if (!mediaPlayer.isPlaying()) {
      mediaPlayer.start();
    }
    return START_STICKY;
  }

  public void onDestroy() {
    if (mediaPlayer.isPlaying()) {
      mediaPlayer.stop();
    }
    mediaPlayer.release();
  }

  public void onCompletion(MediaPlayer _mediaPlayer) {
    stopSelf();
  }

}

您可以像这样启动服务

public class Test extends Activity implements OnClickListener {

  Button startPlaybackButton, stopPlaybackButton;
  Intent playbackServiceIntent;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    startPlaybackButton = (Button) this.findViewById(R.id.StartPlaybackButton);
    stopPlaybackButton = (Button) this.findViewById(R.id.StopPlaybackButton);

    startPlaybackButton.setOnClickListener(this);
    stopPlaybackButton.setOnClickListener(this);

    playbackServiceIntent = new Intent(this, BackgroundAudioService.class);
  }

  public void onClick(View v) {
    if (v == startPlaybackButton) {
      startService(playbackServiceIntent);
      finish();
    } else if (v == stopPlaybackButton) {
      stopService(playbackServiceIntent);
      finish();
    }
  }
}

答案 1 :(得分:0)

请检查下面的实用程序类代码以从您的代码中的任何位置播放音频,并提供所有选项开始、停止、释放声音调整等...

class AudioPlayer {
    private var mPlayer: MediaPlayer? = null
    companion object{
        var mContext:Context?= null
        var audioplayer : AudioPlayer?= null
        fun getInstance(context: Context): AudioPlayer {
            this.mContext = context;
            if(audioplayer == null){
                audioplayer = AudioPlayer()
            }
            return audioplayer!!
        }
    }

    fun getPlayer():MediaPlayer?{
        return mPlayer
    }

    fun adjustSound(){
        try {
            val am: AudioManager =
                mContext!!.getSystemService(Context.AUDIO_SERVICE) as AudioManager

            initVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
            maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

//        am.setStreamVolume(
//            AudioManager.STREAM_MUSIC,
//            am.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
//            0
//        )
//
//        am.adjustVolume(AudioManager.ADJUST_SAME, AudioManager.FLAG_PLAY_SOUND)
        }catch (e:Exception){
            e.printStackTrace()
        }
    }

    fun initMediaPlayer(uriAudio: Uri) {
        try {
//            if (mPlayer == null) {
//                releaseMediaPlayer()
                adjustSound()
//                mPlayer = MediaPlayer()
                mPlayer = MediaPlayer.create(mContext, myUri(uriAudio))
                if (Build.VERSION.SDK_INT >= 21) {
                    val audioAttributes: AudioAttributes =
                        AudioAttributes.Builder()
                            .setUsage(AudioAttributes.USAGE_MEDIA)
                            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                            .build()
                    mPlayer!!.setAudioAttributes(audioAttributes)
                } else {
                    mPlayer!!.setAudioStreamType(AudioManager.STREAM_MUSIC)
                }
//            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    var initVolume : Int = 0
    var maxVolume : Int = 0
    var volumes:Float = -1f
    fun setVolume(progress:Float){
        try {
            volumes =
                (1 - Math.log((100 - progress).toDouble()) / Math.log(100.0)).toFloat()
            if(mPlayer!=null) {
                mPlayer!!.setVolume(volumes, volumes)
            }
        }catch (e:java.lang.Exception){
            e.printStackTrace()
        }
    }

    fun getVolume():Float{
        if(volumes < 0.0){
            volumes = 1.0f
        }
        return volumes
    }

    interface PlayerProgress{
        fun onProgressUpdate(progress:Int)
        fun onComplete(progress:Int)
    }
     var isprePared : Boolean = false
    fun initMediaPlayer(uriAudio: Uri,isAdjusSound:Boolean,playerProgress: PlayerProgress) {
        isprePared = false
        try {
            if(isAdjusSound){
                adjustSound()
            }

//            mPlayer = MediaPlayer()
            mPlayer = MediaPlayer.create(mContext, myUri(uriAudio))
//            try {
//                mPlayer!!.prepare()
//            } catch (e: IOException) {
//                e.printStackTrace()
//            }
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                val speed = 0.25f
//                mPlayer!!.setPlaybackParams(mPlayer!!.getPlaybackParams().setSpeed(speed))
//            }

//            if(isAdjusSound) {
//                val volume = (initVolume / maxVolume).toFloat()
//                mPlayer!!.setVolume(volume, volume)
//            }

            if (Build.VERSION.SDK_INT >= 21) {
                val audioAttributes: AudioAttributes =
                    AudioAttributes.Builder()
//                        .setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED)
//                        .setLegacyStreamType(AudioManager.STREAM_MUSIC)
                        .setUsage(AudioAttributes.USAGE_MEDIA)
                        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                        .build()
                mPlayer!!.setAudioAttributes(audioAttributes)
            } else {
                mPlayer!!.setAudioStreamType(AudioManager.STREAM_MUSIC)
            }

            mPlayer!!.setOnBufferingUpdateListener(OnBufferingUpdateListener{ mediaPlayer: MediaPlayer, i: Int ->
                if(playerProgress!=null) {
                    playerProgress.onProgressUpdate(i)
                }
            })

            mPlayer!!.setOnCompletionListener {
                if(playerProgress!=null) {
                    playerProgress.onComplete(0)
                }
            }

            mPlayer!!.setOnBufferingUpdateListener(OnBufferingUpdateListener{ mediaPlayer: MediaPlayer, i: Int ->
                if(playerProgress!=null) {
                    playerProgress.onProgressUpdate(i)
                }
            })
            mPlayer!!.setOnPreparedListener() {
               isprePared = true
            }

        } catch (e:IllegalStateException) {
            e.printStackTrace();
        }catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun myUri(originalUri: Uri): Uri? {
        var returnedUri: Uri? = null
        returnedUri = if (originalUri.scheme == null) {
            Uri.fromFile(File(originalUri.getPath()))
            // or you can just do -->
            // returnedUri = Uri.parse("file://"+camUri.getPath());
        } else {
            originalUri
        }
        return returnedUri
    }


    fun playMediaPlayer() {
        try {
            if (mPlayer != null && !mPlayer!!.isPlaying/* && isprePared*/) {
                mPlayer!!.start()
            }
        }catch (e:IllegalStateException) {
            e.printStackTrace();
        }catch (e:java.lang.Exception){
            e.printStackTrace()
        }
    }

    fun seektoMediaPlayer(msec:Int) {
        try {
            if (mPlayer != null/*  && isprePared*/) {
                mPlayer!!.seekTo(msec)
            }
        }catch (e:java.lang.Exception){
            e.printStackTrace()
        }
    }

    fun pauseMediaPlayer() {
        try {
            if (mPlayer != null/*  && isprePared*/) {
                mPlayer!!.pause()
            }
        }catch (e:java.lang.Exception){
            e.printStackTrace()
        }
    }

    fun prepareMeidaPlayer(uriAudio: Uri) {
        try {
            if (mPlayer != null) {
                mPlayer!!.setDataSource(mContext!!, uriAudio)
                mPlayer!!.prepare()
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    fun stopMediaPlayer(completstop:Boolean) {
        try {
            if (mPlayer != null) {
                if (completstop) {
                    mPlayer!!.stop()
                } else {
                    mPlayer!!.pause()
                    mPlayer!!.seekTo(0)
                }
            }
        }catch (e:Exception){
            e.printStackTrace()
        }
    }

    fun releaseMediaPlayer(reset: Boolean) {
        try {
            if (mPlayer != null) {
                if(reset){
                    mPlayer!!.reset()
                    mPlayer!!.stop()
                }
                mPlayer!!.release()
                mPlayer = null
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

你可以这样打电话

    AudioPlayer.getInstance(this)
                .initMediaPlayer(Uri.parse(url), false, object : AudioPlayer.PlayerProgress {
                    override fun onProgressUpdate(progress: Int) {
//                        musicDialog.dismiss()
                    }

                    override fun onComplete(progress: Int) {
                        musicDialog.dismiss()
                    }
                })
            AudioPlayer.getInstance(this).playMediaPlayer()