Button的使用(十四):控制音乐播放

播放资源音乐文件

在/res/raw/目录下放a.mp3文件

MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.a)

package com.example.androidtest;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.util.Log;

public class MainActivity extends Activity implements OnCompletionListener, OnTouchListener, OnClickListener {
	
	MediaPlayer mediaPlayer;
	View theView;
	Button stopButton, startButton;
	
	int position = 0;
	
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		stopButton = (Button)findViewById(R.id.StopButton);
		startButton = (Button)findViewById(R.id.StartButton);
		
		stopButton.setOnClickListener(this);
		startButton.setOnClickListener(this);
		
		theView = this.findViewById(R.id.theview);
		theView.setOnClickListener(this);
		
		mediaPlayer = MediaPlayer.create(this, R.raw.a);
		mediaPlayer.setOnCompletionListener(this);
		mediaPlayer.start();
		
	}	
	
	public boolean onTouch(View v, MotionEvent me)
	{
		if (me.getAction() == MotionEvent.ACTION_MOVE) {
			if (mediaPlayer.isPlaying()) {
				position = (int)(me.getX() * mediaPlayer.getDuration() / theView.getWidth());
				Log.d("SEEK", "" + position);
				mediaPlayer.seekTo(position);
			}
		}
		return true;
	}
	
	public void onCompletion(MediaPlayer mp)
	{
		mediaPlayer.start();
		mediaPlayer.seekTo(position);
	}
	
	public void onClick(View v)
	{
		if (v == stopButton) {
			mediaPlayer.pause();
		} else if (v == startButton) {
			mediaPlayer.start();
		}
	}
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button android:text="Start" android:id="@+id/StartButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="Stop" android:id="@+id/StopButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<View android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/theview" />
</LinearLayout>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值