1
我有一個音頻錄製應用程序,它將通過麥克風錄製音頻,錄製完音頻後它將播放音頻,當用戶按播放按鈕時,直到這裏它工作的很好,但我想暫停當用戶點擊暫停按鈕時播放音頻文件。這是我的java代碼。怎麼做?MediaPlayer沒有暫停音頻文件
public class tab1 extends Fragment {
private ViewPager mViewPager;
private Button play,stop,record;
private MediaRecorder myAudioRecorder;
private String outputfile;
public tab1() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootview=inflater.inflate(R.layout.fragment_tab1,container,false);
final ImageButton record=(ImageButton)rootview.findViewById(R.id.record);
final ImageButton stop=(ImageButton) rootview.findViewById(R.id.stop);
final ImageButton play=(ImageButton) rootview.findViewById(R.id.play);
final ImageButton pause=(ImageButton)rootview.findViewById(R.id.pause);
stop.setVisibility(getView().INVISIBLE);
File directorysample=new File(Environment.getExternalStorageDirectory()+separator+"RadioRecords");
directorysample.mkdirs();
String filename = "/recording_" + System.currentTimeMillis() + ".mp3";
final String directory = Environment.getExternalStorageDirectory()+ "/RadioRecords";
outputfile = directory + "/" + filename;
record.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
myAudioRecorder=new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.DEFAULT);
myAudioRecorder.setOutputFile(outputfile);
myAudioRecorder.prepare();
myAudioRecorder.start();
}
catch (IllegalStateException ise){
}catch (IOException ioe){
}
// record.setEnabled(false);
//stop.setEnabled(true);
stop.setVisibility(getView().VISIBLE);
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
myAudioRecorder.stop();
// record.setEnabled(true);
myAudioRecorder.release();
myAudioRecorder=null;
//stop.setEnabled(false);
//play.setEnabled(true);
stop.setVisibility(getView().INVISIBLE);
}
});
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MediaPlayer mediaPlayer=new MediaPlayer();
try {
mediaPlayer.setDataSource(outputfile);
mediaPlayer.prepare();
mediaPlayer.start();
}
catch (Exception e)
{
}
}
});
pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MediaPlayer mediaPlayer=new MediaPlayer();
try {
mediaPlayer.setDataSource(outputfile);
mediaPlayer.prepare();
mediaPlayer.pause();
}
catch (Exception e)
{
}
}
});
return rootview;
}
}
但它可以錄製,停止,播放不停頓,爲什麼? –
仔細看。您使用相同的MediaRecoder進行播放和停止。這就是爲什麼它工作。但是您啓動了兩個用於播放和暫停的新MediaPlayers。當您按PLAY時,會創建新的MediaPlayer並開始播放。在這種情況下,當您按下暫停時,您正在創建另一個新的MediaPlayer,並且前一個已經不存在了。所以前一個繼續播放和「暫停MediaPlayer」沒有任何停止。希望這可以解決問題。對不起,冗長的評論 – tahsinRupam
我做了,但仍然無法正常工作 –