Android使用SoundPool實現(xiàn)播放音頻
最近做一個播放音頻的小功能,使用毛坯界面簡單記錄下(點擊上邊的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<>(); //創(chuàng)建集合存放數(shù)據(jù)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_picture);
initViews();
bindViews();
initDatas();
}
/*初始化數(shù)據(jù)*/
private void initDatas() {
mSoundPool=new SoundPool(3, AudioManager.STREAM_MUSIC,0); //創(chuàng)建音頻對象,參數(shù)為(可容納音頻個數(shù),聲音類型,音頻品質默認為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); //參數(shù)為(要播放的音頻,左聲道音量,右聲道音量,音頻優(yōu)先級,循環(huán)次數(shù),速率)
}
}
另外,音頻文件我放到了項目中,及res中的raw文件。貌似音頻文件可以放入raw或者assets中,不同是raw一般放小型素材并且在代碼中可以直接使用R.raw.xxx調用,而assets不可以。
AndroidStudio添加raw的方法:


點擊OK,然后把音頻文件拖入即可。
(get一個軟件,可以使用格式工廠進行截取音頻,超級方便!?。。?/p>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Android實現(xiàn)從網(wǎng)絡獲取圖片顯示并保存到SD卡的方法
這篇文章主要介紹了Android實現(xiàn)從網(wǎng)絡獲取圖片顯示并保存到SD卡的方法,涉及Android操作多媒體文件及系統(tǒng)硬件設備的相關技巧,需要的朋友可以參考下2015-12-12
Android DSelectorBryant 單選滾動選擇器的實例代碼
本文通過實例代碼給大家介紹了Android DSelectorBryant 單選滾動選擇器的相關知識,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-10-10

