AndroidMedia26 安卓媒体 SoundPool的使用

资源准备:

在这里插入图片描述

视图代码:

<?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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity2SoundActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="播放"
        android:id="@+id/btn_play1" />
</LinearLayout>

java代码:

package com.example.androidmedia26;

import androidx.appcompat.app.AppCompatActivity;

import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.util.HashMap;
import java.util.Map;

public class MainActivity2SoundActivity extends AppCompatActivity {
    private Button btn;
    private SoundPool soundPool;
    private int index = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_activity2_sound);

        btn = findViewById(R.id.btn_play1);
        AudioAttributes audioAttributes = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            audioAttributes = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_GAME).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
            soundPool = new SoundPool.Builder().setAudioAttributes(audioAttributes).build();
        }else {
            soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
        }

        Map<Integer, Integer> musicId = new HashMap<>();
        musicId.put(1, soundPool.load(this, R.raw.yx1, 1));
        musicId.put(2, soundPool.load(this, R.raw.yx2, 1));
        musicId.put(3, soundPool.load(this, R.raw.yx3, 1));
        musicId.put(4, soundPool.load(this, R.raw.yx4, 1));
        musicId.put(5, soundPool.load(this, R.raw.yx5, 1));

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btn.getText().equals("播放")) {
                    btn.setText("下一个");
                }
                soundPool.play(musicId.get(index % 5 + 1), 1, 1, 0, 0, 1);
                index++;
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        soundPool.release();
    }
}

效果:

点击播放前
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值