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ù),聲音類型,音頻品質(zhì)默認(rèn)為0) map.put(1,mSoundPool.load(this,R.raw.abc,100)); //設(shè)置第一個音頻 } /*綁定點擊事件*/ 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調(diào)用,而assets不可以。
AndroidStudio添加raw的方法:
點擊OK,然后把音頻文件拖入即可。
(get一個軟件,可以使用格式工廠進(jìn)行截取音頻,超級方便?。。。?/p>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android實現(xiàn)從網(wǎng)絡(luò)獲取圖片顯示并保存到SD卡的方法
這篇文章主要介紹了Android實現(xiàn)從網(wǎng)絡(luò)獲取圖片顯示并保存到SD卡的方法,涉及Android操作多媒體文件及系統(tǒng)硬件設(shè)備的相關(guān)技巧,需要的朋友可以參考下2015-12-12Android DSelectorBryant 單選滾動選擇器的實例代碼
本文通過實例代碼給大家介紹了Android DSelectorBryant 單選滾動選擇器的相關(guān)知識,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-10-10Android小掛件(APP Widgets)設(shè)計指導(dǎo)
這篇文章主要為大家詳細(xì)介紹了Android小掛件APP Widgets設(shè)計指導(dǎo),具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-12-12