自学Android之播放音频

今天的内容是播放音频,主要用到MediaPlayer类,这个类可以加载音频文件并播放。

MediaPlayer播放的音频文件主要有三个来源:

1.resource资源文件。

2.本地SD卡下的文件。

3.网络文件


我们首先新建一个Activity与布局文件。

布局文件代码如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_media_play"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.myapplication.MediaPlayActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="loadIn"
            android:text="加载内置音乐" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="loadHost"
            android:text="加载本地音乐" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="loadNet"
            android:text="加载网络音乐" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <SeekBar
            android:id="@+id/sb_amp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="isPlayorPause"
            android:src="@android:drawable/ic_media_play" />
    </LinearLayout>
</LinearLayout>


三个按钮分别加载三种来源的文件,进度条显示音频播放的进度,ImageButton控制音频的播放,布局效果如下



MediaPlayer加载资源文件的方法为

     mediaPlayer = MediaPlayer.create(this, R.raw.bszdcq_xzd);

MediaPlayer加载SD卡文件的方法为

try {
            mediaPlayer.setDataSource(this,Uri.parse("/storage/sdcard0/Download/front/单词/例句读音/needle.mp3"));
            mediaPlayer.prepareAsync();
        } catch (Exception e) {
            e.printStackTrace();
        }

MediaPlayer加载网络文件的方法Wie
try {
            mediaPlayer.setDataSource("http://193.168.2.1:8080/examples/mi0123.mp3");
            mediaPlayer.prepareAsync();
        } catch (Exception e) {
            e.printStackTrace();
        }

加载网络文件时不要玩了添加联网权限。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值