Android多媒体之音频播放
Posted 背时的哥哥
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android多媒体之音频播放相关的知识,希望对你有一定的参考价值。
文章目录
1.前言
在android中播放音频文件一般使用MediaPlayer类实现。通过调用其方法可实现对本地音频文件的操作。
2.前期准备
1.在/storage/emulate/0目录下创建Music目录用于存放音频文件
2.添加音频文件到Music中
3.前台页面
1.编写播放列表
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textColor="@color/cardview_dark_background"
android:textAlignment="center"
android:text="music list"
android:background="@color/cardview_shadow_start_color"
android:layout_marginBottom="30dp"
android:gravity="center_horizontal" />
<ListView
android:id="@+id/music_list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="wrap_content"
tools:context=".MainActivity"
>
<TextView
android:id="@+id/musicName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
2.播放页面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_marginBottom="50dp"
android:textAlignment="center"
android:id="@+id/musicTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal" />
<Button
android:id="@+id/play"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Play"/>
<Button
android:id="@+id/pause"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Pause"/>
<Button
android:id="@+id/stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Stop"/>
</LinearLayout>
4.后台逻辑
1.创建实体类
package entity;
public class Music {
private String musicName;
public String getMusicName() {
return musicName;
}
public void setMusicName(String musicName) {
this.musicName = musicName;
}
public Music() {
}
}
2.编写适配器
package com.example.cameraalbumtest;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.List;
import entity.Music;
public class MusicAdapter extends ArrayAdapter<Music>{
private int resourceId;
public MusicAdapter(@NonNull Context context, int resource, List<Music> objects) {
super(context, resource,objects);
resourceId = resource;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
Music music = getItem(position);
View view;
if (convertView == null){
view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
}else {
view = convertView;
}
TextView textView = view.findViewById(R.id.musicName);
textView.setText(music.getMusicName());
return view;
}
}
3.播放列表
package com.example.cameraalbumtest;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import entity.Music;
public class MusicList extends AppCompatActivity {
private List<Music> list = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_list);
//获取该文件夹下的文件
File file = new File(Environment.getExternalStorageDirectory(),"Music");
File[] files = file.listFiles();
//调用方法获取后缀为MP3的文件
initMusic(files);
//将结果交给适配器进行装配
MusicAdapter musicAdapter = new MusicAdapter(MusicList.this,R.layout.music_item,list);
ListView listView = findViewById(R.id.music_list);
listView.setAdapter(musicAdapter);
//设置点击事件
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MusicList.this,MediaPlay.class);
Music music = list.get(position);
String musicName = music.getMusicName();
intent.putExtra("musicName",musicName);
startActivity(intent);
}
});
}
//读取文件中的MP3文件
public void initMusic(File[] files){
for (File file : files) {
Music music = new Music();
if (file.getName().endsWith(".mp3")){
music.setMusicName(file.getName());
list.add(music);
}
}
}
}
4.音频操作
package com.example.cameraalbumtest;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
public class MediaPlay extends AppCompatActivity implements View.OnClickListener {
private MediaPlayer mediaPlayer = new MediaPlayer();
private String musicName;//定义音乐名
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_play);
//获取传来的musicName
Intent intent = getIntent();
musicName = intent.getStringExtra("musicName");
Button play = findViewById(R.id.play);
Button pause = findViewById(R.id.pause);
Button stop = findViewById(R.id.stop);
play.setOnClickListener(this);
pause.setOnClickListener(this);
stop.setOnClickListener(this);
//显示歌曲名称
TextView textView = findViewById(R.id.musicTitle);
textView.setText("歌曲名:"+musicName);
//动态获取访问存储权限
if (ContextCompat.checkSelfPermission(MediaPlay.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MediaPlay.this,new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE
},1);
}else {
//初始化MediaPlay
initMediaPlay(musicName);
}
}
//初始化mediaPlayer
private void initMediaPlay(String musicName){
try{
//根据musicName创建file
File file = new File(Environment.getExternalStorageDirectory(),"Music/"+musicName);
mediaPlayer.setDataSource(file.getPath());//指定音频文件的路径
mediaPlayer.prepare();//让MediaPlayer进入到准备状态
}catch (Exception e){
e.printStackTrace();
}
}
//获取申请权限结果
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 1:
if (grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
initMediaPlay(musicName);
}else {
Toast.makeText(this,"拒绝权限将无法使用程序",Toast.LENGTH_SHORT).show();
finish();
}
break;
default:
}
}
//设置点击事件
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.play:
if (!mediaPlayer.isPlaying()){
mediaPlayer.start();
}
break;
case R.id.pause:
if (mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
break;
case R.id.stop:
if (mediaPlayer.isPlaying()){
mediaPlayer.reset();
initMediaPlay(musicName);
}
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer!=null){
mediaPlayer.stop();
mediaPlayer.release();
}
}
}```
以上是关于Android多媒体之音频播放的主要内容,如果未能解决你的问题,请参考以下文章
初学Android 多媒体之使用SoundPool播放音效 七十六