Android使用SoundPool实现播放音频

发布时间:2019-08-08 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Android使用SoundPool实现播放音频脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

最近做一个播放音频的小功能,使用毛坯界面简单记录下(点击上边的ImageButton播放,下边的ImageView请无视)

Android使用SoundPool实现播放音频

activITy_picture.XMl页面:

 <&#63;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的方法:

Android使用SoundPool实现播放音频

Android使用SoundPool实现播放音频

点击OK,然后把音频文件拖入即可。

(get一个软件,可以使用格式工厂进行截取音频,超级方便!!!)

android教程
脚本网站
android studio

脚本宝典总结

以上是脚本宝典为你收集整理的Android使用SoundPool实现播放音频全部内容,希望文章能够帮你解决Android使用SoundPool实现播放音频所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。