MediaPlayer:延迟长且占用资源多;不支持同时播放多个音频
soundPool:延迟短,且占用资源少,支持多个音频同时播放,但是只能播放短促的音频,如果过长将不能全部播放完毕。
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:id="@+id/relativelayout"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView android:layout_width="match_parent" android:layout_height="wrap_content"
android:id="@+id/listView"
android:entries="@array/bellname"/>
</RelativeLayout>
数组资源:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="bellname">
<item>111111111111</item>
<item>222222222222</item>
<item>333333333333</item>
<item>444444444444</item>
<item>5555555555</item>
<item>6666666666</item>
<item>7777777777</item>
<item>88888888888</item>
</string-array>
</resources>
main:
package com.example.soundpool;
import android.media.AudioAttributes;
import android.media.SoundPool;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView=findViewById(R.id.listView);
AudioAttributes audioAttributes=new AudioAttributes.Builder()//设置音效属性
.setUsage(AudioAttributes.USAGE_MEDIA)//设置音效的使用场景
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)//设置音效类型
.build();
final SoundPool soundPool=new SoundPool.Builder()
.setAudioAttributes(audioAttributes)//设置音效池的属性
.setMaxStreams(10)//设置最多可容纳10个音频流
.build();
//将要播放的音频保存到hashmap对象中
final HashMap<Integer,Integer> soundmap=new HashMap<>();
soundmap.put(0,soundPool.load(this,R.raw.music,1));
soundmap.put(1,soundPool.load(this,R.raw.music,1));
soundmap.put(2,soundPool.load(this,R.raw.music,1));
soundmap.put(3,soundPool.load(this,R.raw.music,1));
soundmap.put(4,soundPool.load(this,R.raw.music,1));
soundmap.put(5,soundPool.load(this,R.raw.music,1));
soundmap.put(6,soundPool.load(this,R.raw.music,1));
soundmap.put(7,soundPool.load(this,R.raw.music,1));
//播放音频
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
soundPool.play(soundmap.get(position),1,1,0,0,1);
}
});
}
}