本文主要是介绍安卓多媒体(视频录制、播放、音效播放),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
安卓多媒体(视频录制、播放、音效播放)
一、MediaRecorder录制视频
使用MediaRecorder能够编写从设备麦克风与相机捕获音视频、保存音视频并(使用MediaPlayer)进行播放的应用。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sut5OuR5-1623675956185)(C:\Users\23737\AppData\Roaming\Typora\typora-user-images\image-20210614202933768.png)]
1.申请权限
<uses-permission android:name="android.permission.RECORD_AUDIO" /><uses-permission android:name="android.permission.CAMERA" />
分别是音频麦克风和视频相机的权限
2.在主活动的布局文件上添加TextureView和一个按钮
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".VideoRecording.MediaRecordActivity"><TextureViewandroid:id="@+id/textureView"android:layout_width="match_parent"android:layout_height="match_parent" /><Buttonandroid:id="@+id/btn_opt"android:onClick="onClick"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="开始"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout>
3.在java文件下编辑代码
package com.example.it_train.VideoRecording;import androidx.appcompat.app.AppCompatActivity;import android.hardware.Camera;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;import com.example.it_train.R;import java.io.File;
import java.io.IOException;public class MediaRecordActivity extends AppCompatActivity {private TextureView mTextureView;private Button mBtn_opt;private Camera camera;private MediaRecorder mediaRecorder;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_media_record);//找到控件mTextureView = findViewById(R.id.textureView);mBtn_opt = findViewById(R.id.btn_opt);}public void onClick(View view){CharSequence text = mBtn_opt.getText();if (TextUtils.equals(text,"开始")) {mBtn_opt.setText("结束");//初始化相机camera = Camera.open();/*** camera.setDisplayOrientation(90);使用在录制视频的时候,显示的效果不是颠倒的* 录制分为 预览 和 真实拍摄 两个阶段* 预览时候是反的,使用 camera.setDisplayOrientation(90);来解决* 真实拍摄是反的,使用mediaRecorder.setOrientationHint(90);来解决*/camera.setDisplayOrientation(90);camera.unlock();mediaRecorder = new MediaRecorder();mediaRecorder.setCamera(camera);//设置视频相关信息mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); //设置音频源 麦克风mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);//设备视频源 摄像头mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);//指定视频文件格式//设置音频编码mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);//设置视频编码mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);//默认是颠倒的,这里要设置回来mediaRecorder.setOrientationHint(90);//设置视频输出文件mediaRecorder.setOutputFile(new File(getExternalFilesDir(""), "a.mp4").getAbsolutePath());mediaRecorder.setVideoSize(640, 480);//设置摄像头预览的画布mediaRecorder.setPreviewDisplay(new Surface(mTextureView.getSurfaceTexture()));try {//录制视频准备mediaRecorder.prepare();} catch (IOException e) {e.printStackTrace();}//进入了录制mediaRecorder.start();}else{mBtn_opt.setText("开始");//回到初始阶段mediaRecorder.stop();mediaRecorder.release();//这里要记得释放cameracamera.stopPreview();camera.release();}}
}
代码注释已经写得很详细了,不懂的看注释就行
二、MediaPlayer播放视频
1.简介:
MediaPlayer类是媒体框架最重要的组成部分之一。此类的对象能够获取、解码以及播放音频和视频,而且只需极少量设置。它支持多种不同的媒体源,例如:
- 本地资源
- 内部URL,例如可能从内容解析器那里获得url
- 外部网址
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hSTHcNjQ-1623675956187)(C:\Users\23737\AppData\Roaming\Typora\typora-user-images\image-20210614203410240.png)]
2.在布局文件下添加TextuerView和按钮
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".VideoRecording.VideoActivity"><TextureViewandroid:id="@+id/textureView"android:layout_width="match_parent"android:layout_height="match_parent" /><Buttonandroid:id="@+id/btn_opt"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="开始"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout>
3.在java文件下编辑代码
package com.example.it_train.VideoRecording;import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;import com.example.it_train.R;import java.io.File;
import java.io.IOException;public class VideoActivity extends AppCompatActivity implements View.OnClickListener,MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener {private TextureView textureView;private Button btn_opt;private MediaPlayer mediaPlayer;@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_video);textureView = findViewById(R.id.textureView);btn_opt = findViewById(R.id.btn_opt);btn_opt.setOnClickListener(this);}@Overridepublic void onClick(View v) {CharSequence text = btn_opt.getText();if (TextUtils.equals(text, "开始")) {btn_opt.setText("结束");mediaPlayer = new MediaPlayer();//设置准备监听mediaPlayer.setOnPreparedListener(this);mediaPlayer.setOnCompletionListener(this);try {//指定视频源mediaPlayer.setDataSource(new File(getExternalFilesDir(""), "a.mp4").getAbsolutePath());} catch (IOException e) {e.printStackTrace();}//设置画布mediaPlayer.setSurface(new Surface(textureView.getSurfaceTexture()));mediaPlayer.prepareAsync();} else {btn_opt.setText("开始");//释放资源mediaPlayer.stop();mediaPlayer.release();}}@Overridepublic void onPrepared(MediaPlayer mp) {mediaPlayer.start();}@Overridepublic void onCompletion(MediaPlayer mp) {btn_opt.setText("开始");mediaPlayer.release();}}
三、使用VideoView来播放视频
1.添加控件
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><VideoViewandroid:id="@+id/videoView"android:layout_width="match_parent"android:layout_height="match_parent" /></androidx.constraintlayout.widget.ConstraintLayout>
2.java文件下编辑代码
package com.enjoy.mediademo;import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.MediaController;
import android.widget.VideoView;import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;import java.io.File;public class VideoViewActivity extends AppCompatActivity implements View.OnClickListener {@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_videoview);VideoView videoView = findViewById(R.id.videoView);//设置一个控制器(可以进行视频播放的操控)MediaController mediaController = new MediaController(this);//给控制器设置一个监听,设置上一个下一个功能mediaController.setPrevNextListeners(this, this);videoView.setMediaController(mediaController);//设置视频路径videoView.setVideoPath(new File(getExternalFilesDir(""), "a.mp4").getAbsolutePath());videoView.start();}@Overridepublic void onClick(View v) {Log.i("VideoView","====");}
}
四、SoundPool播放音效
MediaPlayer虽然也能播放音频,但是它有资源占用量较高、延迟时间较长、不支持多个音频同时播放等缺点。这些缺点决定了MediaPlayer在某些场合的使用情况不会很理想,例如在对时间精准度要求相对较高的场景。而SoundPool一般用来播放密集、急促而又短暂的音效,比如: “滴滴一下,马上出发”。
1.添加控件
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><androidx.recyclerview.widget.RecyclerViewandroid:id="@+id/recyclerView"android:layout_width="match_parent"android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
2.设置适配器
package com.enjoy.mediademo;import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;import java.util.List;public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> implements View.OnClickListener {private final List<SoundActivity.Sound> data;private final Context context;private final RecyclerView recyclerView;private OnItemClickListener listener;public MyAdapter(List<SoundActivity.Sound> data, RecyclerView recyclerView, Context context) {this.data = data;this.recyclerView = recyclerView;this.context = context;}@NonNull@Overridepublic MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {TextView textView = new TextView(context);LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);layoutParams.topMargin = 18;layoutParams.leftMargin = 18;textView.setLayoutParams(layoutParams);textView.setOnClickListener(this);return new MyViewHolder(textView);}@Overridepublic void onBindViewHolder(@NonNull MyViewHolder holder, int position) {((TextView) holder.itemView).setText(data.get(position).getName());}@Overridepublic int getItemCount() {return data.size();}@Overridepublic void onClick(View v) {if (listener != null) {listener.onItemClick(recyclerView.getChildAdapterPosition(v));}}public void setOnItemClickListener(OnItemClickListener listener) {this.listener = listener;}interface OnItemClickListener {void onItemClick(int position);}class MyViewHolder extends RecyclerView.ViewHolder {public MyViewHolder(@NonNull View itemView) {super(itemView);}}
}
3.java文件下编辑
package com.enjoy.mediademo;import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;import java.util.ArrayList;
import java.util.List;public class SoundActivity extends AppCompatActivity implements MyAdapter.OnItemClickListener {private SoundPool soundPool;static class Sound {String name;int soundId;public Sound(String name, int soundId) {this.name = name;this.soundId = soundId;}public int getSoundId() {return soundId;}public String getName() {return name;}}List<Sound> data;@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_sound);RecyclerView recyclerView = findViewById(R.id.recyclerView);LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);recyclerView.setLayoutManager(linearLayoutManager);soundPool = new SoundPool.Builder().setMaxStreams(6).build();data = new ArrayList<>();data.add(new Sound("a4", soundPool.load(this, R.raw.a4, 1)));data.add(new Sound("a5", soundPool.load(this, R.raw.a5, 1)));data.add(new Sound("a6", soundPool.load(this, R.raw.a6, 1)));data.add(new Sound("a7", soundPool.load(this, R.raw.a7, 1)));data.add(new Sound("a8", soundPool.load(this, R.raw.a8, 1)));data.add(new Sound("a9", soundPool.load(this, R.raw.a9, 1)));MyAdapter myAdapter = new MyAdapter(data, recyclerView, this);myAdapter.setOnItemClickListener(this);recyclerView.setAdapter(myAdapter);}@Overridepublic void onItemClick(int position) {Sound sound = data.get(position);soundPool.play(sound.getSoundId(),1.0f, 1.0f, 1, 0, 1.0f);}@Overrideprotected void onDestroy() {super.onDestroy();for (Sound datum : data) {soundPool.unload(datum.getSoundId());}soundPool.release();}
}
五、一点小零碎
?怎么才能使得APP进入之后就显示权限的申请呢
1.首先在manifest申请权限
<uses-permission android:name="android.permission.RECORD_AUDIO" /><uses-permission android:name="android.permission.CAMERA" />
2.在activity的java代码下编辑
public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//申请权限ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO},100);}
}
这篇关于安卓多媒体(视频录制、播放、音效播放)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!