Android使用SoundPool实现播放音频
最近做一个播放音频的小功能,使用毛坯界面简单记录下(点击上边的ImageButton播放,下边的ImageView请无视)
activity_picture.xml页面:
<?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="match_parent" android:orientation="vertical" tools:context=".PictureActivity"> <ImageButton android:id="@+id/ibCogVideo" android:layout_width="100dp" android:layout_height="100dp" android:src="@mipmap/ic_launcher" /> <ImageView android:id="@+id/ivCogPicture" android:layout_width="300dp" android:layout_height="300dp" android:layout_marginTop="100dp" android:src="@mipmap/ic_launcher" /> </LinearLayout>
PictureActivity.java页面:
package com.example.two; 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.ImageButton; import android.widget.ImageView; import java.util.HashMap; public class PictureActivity extends AppCompatActivity implements View.OnClickListener { private ImageButton ibCogVideo; private ImageView ivCogPicture; SoundPool mSoundPool; //一般用来播放短音频 HashMap<Integer,Integer> map=new HashMap<>(); //创建集合存放数据 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_picture); initViews(); bindViews(); initDatas(); } /*初始化数据*/ private void initDatas() { mSoundPool=new SoundPool(3, AudioManager.STREAM_MUSIC,0); //创建音频对象,参数为(可容纳音频个数,声音类型,音频品质默认为0) map.put(1,mSoundPool.load(this,R.raw.abc,100)); //设置第一个音频 } /*绑定点击事件*/ private void bindViews() { ibCogVideo.setOnClickListener(this); } /*初始化控件*/ private void initViews() { ibCogVideo=findViewById(R.id.ibCogVideo); ivCogPicture=findViewById(R.id.ivCogPicture); } /*点击事件*/ @Override public void onClick(View v) { mSoundPool.play(map.get(1),1,1,100,0,1); //参数为(要播放的音频,左声道音量,右声道音量,音频优先级,循环次数,速率) } }
另外,音频文件我放到了项目中,及res中的raw文件。貌似音频文件可以放入raw或者assets中,不同是raw一般放小型素材并且在代码中可以直接使用R.raw.xxx调用,而assets不可以。
AndroidStudio添加raw的方法:
点击OK,然后把音频文件拖入即可。
(get一个软件,可以使用格式工厂进行截取音频,超级方便!!!)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Android 下的 QuickJS Binding 库特性使用详解
这篇文章主要介绍了Android 下的 QuickJS Binding 库特性使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-09-09利用SpannableString和ImageSpan在textview中插入图片的方法
这篇文章主要为大家详细介绍了利用SpannableString和ImageSpan在textview中插入图片的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-11-11Android编程之ListView和EditText发布帖子隐藏软键盘功能详解
这篇文章主要介绍了Android编程之ListView和EditText发布帖子隐藏软键盘功能,结合实例形式分析了Android控件调用、隐藏软键盘的原理与具体实现技巧,需要的朋友可以参考下2017-08-08Android实现状态栏和虚拟按键背景颜色的变化实例代码详解
今天介绍一下,我在项目开发过程中,实现状态栏和虚拟按键背景颜色变化的方法,实现方式是,通过隐藏系统的状态栏和虚拟按键的背景,实现图片和背景显示到状态栏和虚拟按键下方,需要的朋友可以参考下2019-05-05
最新评论