如何添加mp3并在应用程序中播放?

时间:2016-06-30 04:58:02

标签: java android audio mp3

我在下面的代码中尝试了很多。根本没有编译错误。当我以前开始添加的MP3时,在logcat窗口中显示"开始在状态0和#34;中调用。请帮我这个代码。在此先感谢。我也想知道我们何时暂停音频,当我点击开始按钮时,我需要从那里获取歌曲简历(或)是否有任何恢复功能,请在评论部分告诉我。提前致谢。这是我的Java代码



import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


public class MainActivity extends Activity {

	private MediaPlayer mp;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Button mButton = (Button) findViewById(R.id.btnStart);
		Button mButton1 = (Button) findViewById(R.id.btnStop);
		Button mButton2 = (Button) findViewById(R.id.btnPause);

		mp = new MediaPlayer();

		mButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				
				mp.start();
			}
		});
		mButton1.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				
				mp.stop();

			}
		});
		mButton2.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				MediaPlayer.create(MainActivity.this, R.raw.ch);
				mp.pause();

			}
		});




1 个答案:

答案 0 :(得分:0)

创建一个名为AudioClip的类

public class AudioClip {
    public static boolean loop = false;
    public static MediaPlayer mediaPlayer;
    private static SoundPool soundPool;
    public static boolean isplayingAudio = false;
    public static void playAudio(Context c, int id) {
        mediaPlayer = MediaPlayer.create(c, id);
        soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
        if (!mediaPlayer.isPlaying()) {
            isplayingAudio = true;
            mediaPlayer.start();
            mediaPlayer.setLooping(loop);
        }
    }
    public static void stopAudio() {
        isplayingAudio = false;
        mediaPlayer.stop();
    }
}

关于播放音乐的其他活动

Context m = CuteActivity.this;
AudioClip.playAudio(m,  R.raw.ch);\

并停止

            if (AudioClip.isplayingAudio) {
                    AudioClip.stopAudio();
                }