如何停止音乐并在Android中再次播放?

编程入门 行业动态 更新时间:2024-10-28 16:23:38
本文介绍了如何停止音乐并在Android中再次播放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试编写一个简单的Android MediaPlayer代码.我在停止播放歌曲并重新启动时遇到问题.在每个按钮中单击.否则,如果我不停止播放曲目,请在每个按钮中单击歌曲不播放,直到歌曲停止播放.

I am trying to write a simple Android MediaPlayer code. I am facing an issue while stopping a song and restart again. In each button click. Otherwise , if i wont stop the track then , in each button click the song is not playing , it wait until the songs stops.

我的要求是,在每个按钮中单击歌曲应从头开始.

My requirement is , in each button click the song should start from the beginning.

我的代码:

package com.example.musicexample; import android.media.MediaPlayer; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; public class MainActivity extends ActionBarActivity { Button btnPlay; MediaPlayer mPlayer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnPlay = (Button) findViewById(R.id.btnPlay); mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.a); btnPlay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { if(mPlayer.isPlaying()){ mPlayer.stop(); mPlayer.reset(); } mPlayer.start(); } }); } }

在上面的代码中,歌曲随后播放一次,不再播放.

In the above code , the song plays once then , it won't play again.

因此,请仔细阅读,如果我正在播放歌曲,如何停止播放曲目,然后从头开始重新播放呢.

So please go through it , please let me know , how can i stop the track if the song is playing and then restart it from beginning.

推荐答案

您可以尝试以下操作:

MediaPlayer m1 = null; play1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { stopPlaying(); m1=MediaPlayer.create(MainActivity.this, R.raw.a); m1.start(); } }); private void stopPlaying() { if (mp1 != null) { m1.stop(); m1.release(); m1 = null; }

更多推荐

如何停止音乐并在Android中再次播放?

本文发布于:2023-07-11 09:37:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1093608.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:并在   音乐   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!