Android学习之音频、视频的使用

Android的多媒体功能之音频、视频的使用

  1. 音频播放
  1.1 使用MediaPlayer类播放音乐
  1.1.1 使用MediaPlayer的常见流程:
  创建Mediaplayer对象;
  调用setDataSource()方法来设置音频文件;
  再调用prepare()方法使Mediaplayer对象进入准备状态;
  调用start()、stop()、pause()等方法控制音频播放。

    //其它常用方法
    getDuration():得到总的播放时长
    getCurrentPosition():得到当前播放时间
    isPlaying():是否正在播放

  1.1.2 创建MediaPlayer的方式:
  使用构造函数:MediaPlayer mp=new MediaPlayer();
  使用Create方法:mp=MediaPlayer.create(this, R.raw.test);
  1.1.3 可播放的文件主要有三个来源:
  在程序中自带的resource资源:使用资源名
  在SD卡或其他文件路径下的媒体文件:使用文件名
  网络上的媒体文件:使用URL
  1.1.4 通过定时器来跟踪播放进度:Timer
  定时器类功能:在规定的时间长度后,循环执行特定的任务。
  使用方法:
  通过构造函数初始化Timer对象;
  调用该对象的schedule(Timetask task, int delay, int period)方法。
    task:TimerTask类对象,通过实现其run()方法来定时执行任务。
    delay:表示多长时间后开始执行。
    Period:执行的时间间隔。

  ☆☆☆Android Studio实现音乐播放器
  1.打开Android Studio,新建工程后,在activity_main.xml中界面设计。
  在这里插入图片描述

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="lession.example.com.androidlession2019616.MainActivity">
    
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        
        <TextView
            android:text="TextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textView"
            android:textColor="@android:color/black"
            android:textSize="20sp" />
            
        <SeekBar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/seekBar" />
            
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            
            <Button
                android:text="Play"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAllCaps="false"
                android:id="@+id/button"
                android:layout_weight="1"
                android:textSize="20sp" />
                
            <Button
                android:text="Pause"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAllCaps="false"
                android:id="@+id/button2"
                android:layout_weight="1"
                android:textSize="20sp" />
                
            <Button
                android:text="Stop"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAllCaps="false"
                android:id="@+id/button3"
                android:layout_weight="1"
                android:textSize="20sp" />
                
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>

  在res中新建raw文件夹,放入一首音乐。
  在这里插入图片描述
  2.在MainActivity中,编写代码。

package lession.example.com.androidlession2019616;

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    SeekBar sBar;
    MediaPlayer mPlayer;
    Timer mTimer;
    int mDuration;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tv = (TextView) findViewById(R.id.textView);
        Button btPlay = (Button) findViewById(R.id.button);
        Button btPause = (Button) findViewById(R.id.button2);
        Button btStop = (Button) findViewById(R.id.button3);
        sBar = (SeekBar) findViewById(R.id.seekBar);
        tv.setText("音乐播放器");
        
        btPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPlayer!=null){
                    mPlayer.start();
                    return;
                }
                try {
                    mPlayer = MediaPlayer.create(MainActivity.this,R.raw.again);
                    mDuration = mPlayer.getDuration();
                    sBar.setMax(mDuration);
                    mPlayer.start();
                    if (mTimer==null){
                        mTimer = new Timer();
                        mTimer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                if (mPlayer.isPlaying()==true){
                                    int mPosition = mPlayer.getCurrentPosition();
                                    sBar.setProgress(mPosition);
                                }
                            }
                        },0,1000);
                    }
                }catch (Exception e){
                    Toast.makeText(MainActivity.this,"音乐播放失败",
                            Toast.LENGTH_LONG).show();
                }
            }
        });
        
        btPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPlayer!=null && mPlayer.isPlaying()==true){
                    mPlayer.pause();
                }
            }
        });
        
        btStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPlayer!=null){
                    mTimer.cancel();
                    mTimer = null;
                    mPlayer.stop();
                    mPlayer.release();
                    mPlayer = null;
                    sBar.setProgress(0);
                }
            }
        });
        
        sBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (mPlayer==null){
                    seekBar.setProgress(0);
                }else if (fromUser==true){
                    mPlayer.seekTo(progress);
                }
            }
            
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                if (mPlayer==null){
                    Toast.makeText(MainActivity.this,"音乐播放器尚未准备好",
                            Toast.LENGTH_LONG).show();
                }
            }
            
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        
    }
}

  运行结果:
在这里插入图片描述
  1.2 使用SoundPool类播放音乐
  1.2.1 SoundPool与MediaPlayer的区别:
  MediaPlayer:
    一般用于播放比较大的音频文件;
    播放音频文件占用资源较高,延迟的时间较长;
    不支持多个音频的播放。
  SoundPool:
    一般用于播放密集,短促的音频,可支持播放多个音频文件;
    支持自行设置音频的品质和播放比率;
    播放音频资源占用小,时间延迟小。
  1.2.2 SoundPool的使用
  使用构造函数获取SoundPool对象;

SoundPool(int maxStreams, int streamType, int srcQuality)

  使用load()方法导入音频文件,不同的资源文件,有不同的加载方式;
  调用play方法实现播放。

play(int soundID, float lVolume,float rVolume, int priority, int loop, float rate)
//soundID:load音频后获取的ID;Volume:左右音量,默认1
//priority:优先级,越大越高
//loop:是否循环(0为不循环,-1为循环)
//rate:声音的播放速率,默认是1

  ☆☆☆Android Studio实现SoundPool的使用
  1.打开Android Studio,新建工程后,在activity_main.xml中界面设计,在res中新建raw文件夹,放入三首音乐。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="lession.example.com.learnsoundpool.MainActivity">
    
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        
        <Button
            android:text="音乐播放1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/button"
            android:onClick="onClick"
            android:textColor="@android:color/holo_red_dark" />
            
        <Button
            android:text="音乐播放2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/button2"
            android:onClick="onClick"
            android:textColor="@android:color/holo_red_dark" />
            
        <Button
            android:text="音乐播放3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/button3"
            android:onClick="onClick"
            android:textColor="@android:color/holo_red_dark" />
            
    </LinearLayout>
</RelativeLayout>

  2.在MainActivity中,编写代码。

package lession.example.com.learnsoundpool;

import android.media.AudioManager;
import android.media.SoundPool;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    SoundPool soundPool;
    int sid1,sid2,sid3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //创建一个最多支持5个流同时播放的类型标记为音乐的SoundPool
        soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC,0);
        //使用load加载不同的音乐文件并获取ID
        sid1 = soundPool.load(getApplicationContext(),R.raw.again,1);
        sid2 = soundPool.load(getApplicationContext(),R.raw.snowflakes,1);
        sid3 = soundPool.load(getApplicationContext(),R.raw.weddingindream,1);
        //使用OnLoadCompleteListener监听是否加载完成
        soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                Toast.makeText(getApplicationContext(),"音乐播放",Toast.LENGTH_LONG).show();
            }
        });

    }
    public void onClick(View v){
        switch (v.getId()){
            case R.id.button:
                soundPool.play(sid1,1,1,0,0,1);
                break;
            case R.id.button2:
                soundPool.play(sid2,1,1,0,0,1);
                break;
            case R.id.button3:
                soundPool.play(sid3,1,1,0,0,1);
                break;
        }
    }
}

  运行结果:
在这里插入图片描述
  2. 视频播放
  2.1 使用VideoView实现视频播放
  使用VideoView的步骤:
    创建VideoView对象:在布局界面中定义VideoView组件;
    加载指定的视频,通过调用VideoView的下列两个方法来实现;

      setVidePath(String path);//加载path文件代表的视频
      setVideoURI(Uri uri);//加载uri所对应的视频

    控制视频的播放:调用VideoView的start()、stop()、psuse()方法实现,可以和MediaController类结合使用来实现视频控制。

  ☆☆☆Android Studio实现视频的播放
  1.打开Android Studio,新建工程后,在activity_main.xml中界面设计,在res中新建raw文件夹,放入一段视频。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="lession.example.com.androidlession2019616_2.MainActivity">
    
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            
            <Button
                android:text="播放"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/button"
                android:layout_weight="1"
                android:textColor="@android:color/holo_red_dark" />
                
            <Button
                android:text="暂停"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/button2"
                android:layout_weight="1"
                android:textColor="@android:color/holo_red_dark" />
                
            <Button
                android:text="重播"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/button3"
                android:layout_weight="1"
                android:textColor="@android:color/holo_red_dark" />
                
            <Button
                android:text="停止"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/button4"
                android:layout_weight="1"
                android:textColor="@android:color/holo_red_dark" />
                
        </LinearLayout>
        
        <VideoView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/videoView" />
            
    </LinearLayout>
</RelativeLayout>

  2.在MainActivity中,编写代码。

package lession.example.com.androidlession2019616_2;

import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {
    private VideoView mVideoView;
    private Button btPlay,btPause,btResume,btStop;
    private MediaController mediaController;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取VideoView、Button实例
        mVideoView = (VideoView) findViewById(R.id.videoView);
        btPlay = (Button) findViewById(R.id.button);
        btPause = (Button) findViewById(R.id.button2);
        btResume = (Button) findViewById(R.id.button3);
        btStop = (Button) findViewById(R.id.button4);
//        //设置视频路径
//        mVideoView.setVideoURI(Uri.parse(
//                "android.resource://lession.example.com.androidlession2019616_2/"
//                        +R.raw.video));
//        //与MediaController关联
//        mVideoView.setMediaController(new MediaController(MainActivity.this));
//        mVideoView.start();
        btPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //设置视频路径
                mVideoView.setVideoURI(Uri.parse(
                        "android.resource://lession.example.com.androidlession2019616_2/" + R.raw.video));
                mVideoView.start();
            }
        });
        btPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mVideoView.isPlaying()) {
                    mVideoView.pause();
                } else {
                    mVideoView.start();
                }
            }
        });
        btResume.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mVideoView.resume();
            }
        });
        btStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mVideoView.stopPlayback();
            }
        });
    }
    
}

  3.在AndroidManifest.xml添加权限。

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

  运行结果:
在这里插入图片描述

  2.2 使用MediaPlayer+SurfaceView的方式实现视频播放
  MediaPlayer主要用来播放音频,无图像输出界面,使用SurfaceView来显示图像。
  主要设计步骤:
  调用MediaPlayer.setDataSource()方法设置要播放的资源;
  调用MediaPlayer.setDisplay(holder)设置surfaceHolder:surfaceHolder可以通过surfaceview的getHolder()方法获得;
  调用MediaPlayer.prepare()来准备;
  调用MediaPlayer.start()来播放视频。

  ☆☆☆Android Studio使用MediaPlayer+SurfaceView实现视频的播放
  1.打开Android Studio,新建工程后,在activity_main.xml中界面设计,在res中新建raw文件夹,放入一段视频。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="lession.example.com.learnsurfaceview.MainActivity">
    
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        
        <SurfaceView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/surfaceView" />
    </LinearLayout>
</RelativeLayout>

  2.在MainActivity中,编写代码。

package lession.example.com.learnsurfaceview;

import android.app.Service;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    MediaPlayer mediaPlayer;
    SurfaceView surfaceView;
    SurfaceHolder surfaceHolder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mediaPlayer = MediaPlayer.create(this,R.raw.video);
        surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        surfaceHolder = surfaceView.getHolder();
        try{
            if (mediaPlayer!=null)
                mediaPlayer.stop();
            surfaceHolder.addCallback(new MyCallBack());
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.prepare();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    private class MyCallBack implements SurfaceHolder.Callback{
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            mediaPlayer.setDisplay(holder);
        }
        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        }
        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
        
        }
    }
    @Override
    protected void onDestroy() {
        if (mediaPlayer.isPlaying())
            mediaPlayer.stop();
        mediaPlayer.release();
        super.onDestroy();
    }
}

  运行结果:
在这里插入图片描述

  这就是音频、视频的使用,如果转载以及CV操作,请务必注明出处,谢谢!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值