当前位置: 移动技术网 > IT编程>移动开发>Android > Android使用SoundPool实现播放音频

Android使用SoundPool实现播放音频

2019年07月23日  | 移动技术网IT编程  | 我要评论

姑嫂丸,黄崇俊,seo经验分享

最近做一个播放音频的小功能,使用毛坯界面简单记录下(点击上边的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一个软件,可以使用格式工厂进行截取音频,超级方便!!!)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网