AudioFragment.java
package com.dasudian.hellomoon;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class AudioFragment extends Fragment {
// 播发音频
private AudioPlayer mPlayer = new AudioPlayer();
private Button mPlayButton;
private Button mStopButton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_audio, container, false);
mPlayButton = (Button)v.findViewById(R.id.hellomoon_playButton);
mPlayButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPlayer.play(getActivity());
}
});
mStopButton = (Button)v.findViewById(R.id.hellomoon_stopButton);
mStopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPlayer.stop();
}
});
return v;
}
@Override
public void onDestroy() {
super.onDestroy();
mPlayer.stop();
}
}
AudioPlayer.java
package com.dasudian.hellomoon;
import android.content.Context;
import android.media.MediaPlayer;
/**
* Created by liuwei on 16/4/9.
*/
public class AudioPlayer {
private MediaPlayer mPlayer;
public void stop() {
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
public void play(Context c) {
// 播放新的前先把原来的关闭
stop();
mPlayer = MediaPlayer.create(c, R.raw.one_small_step);
// 播放完了就停止
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
stop();
}
});
mPlayer.start();
}
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:src="@mipmap/armstrong_on_moon"
android:contentDescription="@string/hellomoon_description"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerInside"
android:layout_weight="1"/>
<TableRow
android:gravity="center|bottom"
android:layout_weight="0">
<Button
android:id="@+id/hellomoon_playButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hellomoon_play"/>
<Button
android:id="@+id/hellomoon_stopButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hellomoon_stop"/>
</TableRow>
</TableLayout>