** Mediaplay最详细使用方法**
在前几个星期吧 小编的公司 一直有播放音频的这个 模块 但是因为小编 接触这块比较少 所以走了很多的 “丸子” 比如 狂点 播放 暂停按钮 会崩掉 new出好几个 meidiaplay 的 辣鸡操作 但是都改正了 而且 很全面 使用起来 也很简单
**首先我先说明一下我们公司的需求 **
进入背诵界面之后 先判断本地有没有 当前需要播放的音频文件 有的话 直接播放 没有 下载完成之后 播放 可以暂停 ok 那么 咱们开始
先看下效果 因为我是平板 录完视频之后是竖着的 所以大家凑活看
1.这个是本地文件有的情况下 直接播放 可以暂停结束
2.本地没有的情况下会下载 下载完成之后 播放
下边粘上我的代码
xml 布局 是一个Checkbox 进度条就是 系统的 seekbar 就是自己加了一个 样式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/llyt_play" android:layout_width="match_parent" android:layout_height="70dp" android:layout_margin="5dp" android:gravity="center_vertical" android:orientation="horizontal"> <CheckBox android:id="@+id/chk_play_btn" android:layout_width="25dp" android:layout_height="25dp" android:layout_marginLeft="20dp" android:background="@drawable/play_btn_play_pause_selector" android:button="@null" /> <SeekBar android:id="@+id/audio_play_bar" android:layout_width="0dp" android:layout_weight="16" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:maxHeight="3dp" android:minHeight="3dp" android:progressDrawable="@drawable/shape_seek_bg" android:thumb="@mipmap/ann1" /> <LinearLayout android:id="@+id/llyt_time" android:layout_width="0dp" android:layout_weight="3" android:layout_height="70dp" android:layout_alignParentRight="true" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:gravity="center_vertical" android:orientation="horizontal"> <TextView android:id="@+id/tv_start_time_show" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:textSize="17sp" android:text="00:00" /> <TextView android:id="@+id/tv_xie" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="3dp" android:layout_marginRight="3dp" android:text="/" /> <TextView android:id="@+id/tv_stop_show_time" android:layout_width="wrap_content" android:textSize="17sp" android:layout_height="wrap_content" android:layout_centerVertical="true" android:text="00:00" /> </LinearLayout> </LinearLayout> </RelativeLayout>
然后 check box 的选择器 以及 seekbar的 设置
首先 checkbox 的 @drawable/play_btn_play_pause_selector
1
2
3
4
5
6
7<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/iv_stop" android:state_checked="true"/> <item android:drawable="@drawable/iv_start" /> </selector> //这边图片的大家可以替换自己的
接下来是 seekbar的 @drawable/shape_seek_bg 是一个层次集合 里边都有注解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@android:id/background" android:height="5dp" > <!--整体进度条的颜色 背景 --> <shape> <corners android:radius="5dp" /> <solid android:color="#CFDCF6" /> </shape> </item> <item android:id="@android:id/secondaryProgress" android:height="5dp" > <!--二进度条进度条的颜色 背景 --> <clip> <shape> <corners android:radius="5dp" /> <solid android:color="#CFDCF6" /> </shape> </clip> </item> <item android:id="@android:id/progress" android:height="5dp" > <!-- 一 进度条的颜色 背景 --> <clip> <shape> <corners android:radius="5dp" /> <solid android:color="@color/login_tit" /> </shape> </clip> </item> </layer-list>
然后 下边粘上我的代码因为这个是我项目中的代码 所以大家“烤”的时候需要自己 过滤一下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.Intent; import android.media.MediaPlayer; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import com.example.juanshichang.utils.ToastUtil; import com.xhly.easystud.utils.Util; import com.flyco.roundview.RoundTextView; import com.xhkjedu.xhstudy.utils.L; import com.xhly.easystud.R; import com.xhly.easystud.base.BaseMvpActivity; import com.xhly.easystud.bean.ReciteResultBean; import com.xhly.easystud.config.BaseConfig; import com.xhly.easystud.http.Content; import com.xhly.easystud.utils.DownloadUtil; import com.xhly.easystud.utils.ZJFileUtil; import com.xhly.easystud.zhan.recite.presenter.ReciteResultPresenterImpl; import com.xhly.easystud.zhan.recite.recitecontract.ReciteResultContract; import java.io.File; import java.util.ArrayList; public class ReciteResultActivity extends BaseMvpActivity<ReciteResultPresenterImpl> implements View.OnClickListener, ReciteResultContract.MyView { private static final String TAG = "ReciteResultActivity"; private TextView tvBack; private TextView tvNumberReally; private CheckBox chkPlaybtn; private SeekBar andioPlayBtn; private Integer mRsid; private ReciteResultPresenterImpl reciteResultPresenter; private TextView tvTitle; private TextView tvContent; private TextView tvFinishTime; private RoundTextView tvAnswer; private RoundTextView tvOrigin; private String answertxt; private String recitecont; private Integer costtime; private TextView tvStopShowTime; private String answerpath; private boolean isStop;//线程标志位 private boolean isPlaying = false; private ArrayList<String> wavfileurllist = new ArrayList<>(); private ProgressDialog progressDialog; private Integer costtime1; private String getsubwavfilename; private String wavfileurl; private TextView tvStartTimeShow; public MediaPlayer mediaPlayer = null; private Thread thread; @Override protected int getContentView() { return R.layout.activity_recite_result; } //运用Handler中的handleMessage方法接收子线程传递的信息 @SuppressLint("HandlerLeak") private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); // 将SeekBar位置设置到当前播放位置 andioPlayBtn.setProgress(msg.what); //获得音乐的当前播放时间 tvStartTimeShow.setText(Util.Companion.getTimeMS(msg.what / 1000)); } }; @Override protected void initView() { changeStatusColor(true); Intent intent = getIntent(); mRsid = intent.getIntExtra(Content.PSID, 0); tvBack = findViewById(R.id.tv_back); tvNumberReally = findViewById(R.id.tv_number_really); chkPlaybtn = findViewById(R.id.chk_play_btn); andioPlayBtn = findViewById(R.id.audio_play_bar); tvTitle = findViewById(R.id.tv_title); tvContent = findViewById(R.id.tv_content); tvStartTimeShow = findViewById(R.id.tv_start_time_show); tvNumberReally = findViewById(R.id.tv_number_really); tvFinishTime = findViewById(R.id.tv_finish_time); tvAnswer = findViewById(R.id.tv_answer); tvOrigin = findViewById(R.id.tv_origin); tvStopShowTime = findViewById(R.id.tv_stop_show_time); tvAnswer.getDelegate().setBackgroundColor(getResources().getColor(R.color.logBut)); tvAnswer.setTextColor(this.getResources().getColor(R.color.white)); reciteResultPresenter = new ReciteResultPresenterImpl(); reciteResultPresenter.attachView(this); initonclicklistener(); } private void initonclicklistener() { tvBack.setOnClickListener(this); tvOrigin.setOnClickListener(this); tvAnswer.setOnClickListener(this); chkPlaybtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (b) { if (mediaPlayer != null) { if(!mediaPlayer.isPlaying()){ isStop = false; mediaPlayer.start(); if (thread != null) { thread.start(); } else { thread = new Thread(new MuiscThread()); thread.start(); } } } else { satrtPlayWav(); //刚开始为播放的时候 点击开始播放 并且更换状态 } } else { //如果在播放中,立刻暂停。 chkPlaybtn.setChecked(false); if (mediaPlayer != null) { mediaPlayer.pause(); } } } }); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.tv_back: finish(); isStop = true; break; case R.id.tv_answer: tvAnswer.getDelegate().setStrokeColor(getResources().getColor(R.color.logBut)); tvAnswer.getDelegate().setBackgroundColor(getResources().getColor(R.color.logBut)); tvAnswer.setTextColor(getResources().getColor(R.color.white)); tvOrigin.getDelegate().setBackgroundColor(getResources().getColor(R.color.white)); tvOrigin.getDelegate().setStrokeColor(getResources().getColor(R.color.gray_border)); tvOrigin.setTextColor(getResources().getColor(R.color.black)); tvContent.setText(answertxt); break; case R.id.tv_origin: tvOrigin.getDelegate().setStrokeColor(getResources().getColor(R.color.logBut)); tvOrigin.getDelegate().setBackgroundColor(getResources().getColor(R.color.logBut)); tvOrigin.setTextColor(getResources().getColor(R.color.white)); tvAnswer.getDelegate().setBackgroundColor(getResources().getColor(R.color.white)); tvAnswer.getDelegate().setStrokeColor(getResources().getColor(R.color.gray_border)); tvAnswer.setTextColor(getResources().getColor(R.color.black)); tvContent.setText(recitecont); break; } } @Override protected void initData() { showLoading(); reciteResultPresenter.getReciteResultData(mRsid); } @Override public void getReciteResultView(ReciteResultBean reciteResultBean) { answerpath = reciteResultBean.getAnswerpath(); String recitetitle = reciteResultBean.getRecitetitle(); recitecont = reciteResultBean.getRecitecont(); answertxt = reciteResultBean.getAnswertxt(); Integer userscore = reciteResultBean.getUserscore(); Integer stoptime = reciteResultBean.getStoptime(); costtime1 = reciteResultBean.getCosttime(); //后台获取到的时间 String Stringstoptime = Util.Companion.getTimedate(stoptime); tvFinishTime.setText("完成时间 : " + Stringstoptime); tvTitle.setText(recitetitle); tvContent.setText(answertxt); tvNumberReally.setText(String.valueOf(userscore)); tvTitle.setText(recitetitle); } private void satrtPlayWav() { wavfileurl = ZJFileUtil.AUDIO_WAV_DIR(this); File file = new File(wavfileurl); File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { File file1 = files[i]; if (file1 != null) { wavfileurllist.add(file1.getName()); } else { } } getsubwavfilename = answerpath.substring(answerpath.lastIndexOf("/") + 1); if (wavfileurllist != null && wavfileurllist.contains(getsubwavfilename)) { startplsywav(getsubwavfilename); } else { chkPlaybtn.setChecked(false); progressDialog = new ProgressDialog(ReciteResultActivity.this); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setTitle("正在下载"); progressDialog.setMessage("请稍后..."); progressDialog.setProgress(0); progressDialog.setMax(100); progressDialog.show(); progressDialog.setCancelable(false); DownloadUtil.get().download(BaseConfig.showImageUrl + answerpath, ZJFileUtil.AUDIO_WAV_DIR(this), getsubwavfilename, new DownloadUtil.OnDownloadListener() { @Override public void onDownloadSuccess(File file) { runOnUiThread(new Runnable() { @Override public void run() { String getokwavurl = file.getName().substring(file.getName().lastIndexOf("/") + 1); if (getokwavurl.equals(getsubwavfilename)) { ToastUtil.Companion.showToast(ReciteResultActivity.this, "下载完成"); chkPlaybtn.setChecked(true); } } }); } @Override public void onDownloading(int progress) { runOnUiThread(new Runnable() { @Override public void run() { progressDialog.setProgress(progress); if (progress == progressDialog.getMax()) { progressDialog.dismiss(); } } }); } @Override public void onDownloadFailed(Exception e) { runOnUiThread(new Runnable() { @Override public void run() { ToastUtil.Companion.showToast(ReciteResultActivity.this, "下载失败"); progressDialog.dismiss(); } }); } }); } } private void startplsywav(String filename) { isStop = false; chkPlaybtn.setChecked(true); mediaPlayer = new MediaPlayer(); try { mediaPlayer.setDataSource(wavfileurl + File.separator + filename); mediaPlayer.prepareAsync(); } catch (Exception e) { e.printStackTrace(); } mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { mediaPlayer.start(); andioPlayBtn.setMax(mediaPlayer.getDuration()); int stopshowtime = mediaPlayer.getDuration() / 1000; //h直接获取本地的 文件时间 String Stringfinishtime = Util.Companion.getTimeMS(stopshowtime); tvStopShowTime.setText(Stringfinishtime); chkPlaybtn.setClickable(true); } }); thread = new Thread(new MuiscThread()); // 启动线程 thread.start(); mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { isStop = true; if (mediaPlayer != null) { if (mediaPlayer.isPlaying()) { mediaPlayer.stop(); mediaPlayer.release(); } } if (thread != null) { thread.interrupt(); } // tvStartTimeShow.setText("00:00"); // andioPlayBtn.setProgress(0); chkPlaybtn.setChecked(false); } }); } @Override protected void onDestroy() { super.onDestroy(); if (mediaPlayer != null && handler != null && thread != null) { mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer = null; thread.interrupt(); isStop = true; handler.removeCallbacks(thread); } } //建立一个子线程实现Runnable接口 class MuiscThread implements Runnable { @Override //实现run方法 public void run() { //判断音乐的状态,在不停止与不暂停的情况下向总线程发出信息 while (mediaPlayer != null && !isStop) { try { //发出的信息 handler.sendEmptyMessage(mediaPlayer.getCurrentPosition()); // 每100毫秒更新一次位置 Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } if (isStop) { thread.interrupt(); break; } } } } }
加上我使用的下载工具类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99/** * 文件下载工具类(单例模式) * Created on 2017/10/16. */ public class DownloadUtil { private static DownloadUtil downloadUtil; private final OkHttpClient okHttpClient; public static DownloadUtil get() { if (downloadUtil == null) { downloadUtil = new DownloadUtil(); } return downloadUtil; } private DownloadUtil() { okHttpClient = new OkHttpClient(); } /** * @param url 下载连接 * @param destFileDir 下载的文件储存目录 * @param destFileName 下载文件名称 * @param listener 下载监听 */ public void download(final String url, final String destFileDir, final String destFileName, final OnDownloadListener listener) { Request request = new Request.Builder().url(url).build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // 下载失败监听回调 listener.onDownloadFailed(e); } @Override public void onResponse(Call call, Response response) throws IOException { InputStream is = null; byte[] buf = new byte[2048]; int len = 0; FileOutputStream fos = null; // 储存下载文件的目录 File dir = new File(destFileDir); if (!dir.exists()) { dir.mkdirs(); } File file = new File(dir, destFileName); try { is = response.body().byteStream(); long total = response.body().contentLength(); fos = new FileOutputStream(file); long sum = 0; while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); sum += len; int progress = (int) (sum * 1.0f / total * 100); // 下载中更新进度条 listener.onDownloading(progress); } fos.flush(); // 下载完成 listener.onDownloadSuccess(file); } catch (Exception e) { listener.onDownloadFailed(e); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (fos != null) fos.close(); } catch (IOException e) { } } } }); } public interface OnDownloadListener { /** * @param file 下载成功后的文件 */ void onDownloadSuccess(File file); /** * @param progress 下载进度 */ void onDownloading(int progress); /** * @param e 下载异常信息 */ void onDownloadFailed(Exception e); } }
大家 看了有不懂的 可以问我 问我我的地方 我到时候加个注释 再给大家说一下 这样写的好处
最后
以上就是冷静宝贝最近收集整理的关于Android——Mediaplay音频播放最详细最全面使用方法-以及自定义seekbar 样式的全部内容,更多相关Android——Mediaplay音频播放最详细最全面使用方法-以及自定义seekbar内容请搜索靠谱客的其他文章。
发表评论 取消回复