最近需要实现一个简易的播放器的功能,来播放本地的音乐功能,首先想到了MediaPlayer,但是有些方法又不是记得很清楚,查找了一些比较不错的例子,基于基础上来完成自己想要的功能:
功能:
1.播放本地音频文件,显示进度条seekbar,显示播放的开始时间与结束时间,随播放的进度而改变,
2.监听来电,当打电话进来的时候,暂停播放音频,记录当前播放位置,电话结束后,用户再次点击播放,从上一次的位置继续播放
3.用户在播放过程中可以随时移动seekbar的位置,来听自己想要听得位置
4.用户在点击停止的时候,也可以随时移动seekbar的位置,同时开始时间也随之改变,用户点击播放的时候,从当前位置开始播放
附上几张实现的功能图
下面附上自己实现的代码,有需要的直接复制到项目中运行即可,看到效果
1.activity_play_music.xml
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="20sp"
android:text="Android实现简易音乐器播放"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
>
<TextView
android:layout_marginLeft="10dp"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:id="@+id/tv_start"
/>
<SeekBar
android:layout_width="270dp"
android:layout_height="wrap_content"
android:id="@+id/seekbar"
/>
<TextView
android:layout_width="40dp"
android:layout_height="wrap_content"
android:id="@+id/tv_end"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center_horizontal"
>
<ImageButton
android:layout_width="60dp"
android:layout_height="60dp"
android:id="@+id/bt_media"
android:src="@android:drawable/ic_media_play"