Android 按钮Button点击音效

一、新建工程

编译运行,确保工程无误,这里不过多赘述。

二、UI布局

添加两个播放音效Button

html 复制代码
<?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"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_marginTop="100dp"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="vertical"
            android:layout_margin="20dp"
            android:layout_height="wrap_content">
            <Button
                android:layout_width="match_parent"
                android:id="@+id/btn_start1"
                android:text="start 1"
                android:layout_height="wrap_content">

            </Button>

            <Button
                android:layout_width="match_parent"
                android:id="@+id/btn_start2"
                android:text="start 2"
                android:layout_height="wrap_content">

            </Button>

            <Button
                android:layout_marginTop="10dp"
                android:id="@+id/btn_stop"
                android:text="stop"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

            </Button>
        </LinearLayout>
    </LinearLayout>

</LinearLayout>

三、功能实现

Mainactivity.java中添加如下代码

java 复制代码
package com.example.sing_test;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    private Button btn_start1, btn_start2, btn_stop;
    SoundPool sp;//声明SoundPool的引用
    HashMap<Integer, Integer> hm;//声明HashMap来存放声音文件
    int currStaeamId;//当前正播放的streamId

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

        /* ------------------------------------------------------------------------------------- */
        // 隐藏状态栏方法
        View decorView = getWindow().getDecorView();
        int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
        decorView.setSystemUiVisibility(option);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        // 隐藏标题栏
        ActionBar actionBar = getSupportActionBar();
        assert actionBar != null;
        actionBar.hide();

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//隐藏状态栏但不隐藏状态栏字体
        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //隐藏状态栏,并且不显示字体
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//实现状态栏文字颜色为暗色
        }
        /* ------------------------------------------------------------------------------------- */

        btn_start1 = findViewById(R.id.btn_start1);
        btn_start2 = findViewById(R.id.btn_start2);
        btn_stop = findViewById(R.id.btn_stop);

        initSoundPool();//初始化声音池的方法

        btn_start1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                playSound(1, 0);//播放1号声音资源,且播放一次
                //提示播放即时音效
                Toast.makeText(MainActivity.this, "播放即时音效", Toast.LENGTH_SHORT).show();
            }
        });
        btn_start2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                playSound(2, 0);//播放1号声音资源,且播放一次
                //提示播放即时音效
                Toast.makeText(MainActivity.this, "播放即时音效", Toast.LENGTH_SHORT).show();
            }
        });

        btn_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sp.stop(currStaeamId);//停止正在播放的某个声音
                //提示停止播放
                Toast.makeText(MainActivity.this, "停止播放即时音效", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void playSound(int sound, int loop) {//获取AudioManager引用
        AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        //获取当前音量
        float streamVolumeCurrent = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        //获取系统最大音量
        float streamVolumeMax = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        //计算得到播放音量
        float volume = streamVolumeCurrent / streamVolumeMax;
        //调用SoundPool的play方法来播放声音文件
        currStaeamId = sp.play(hm.get(sound), volume, volume, 1, loop, 1.0f);
    }

    private void initSoundPool() {//初始化声音池
        sp = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);//创建SoundPool对象
        hm = new HashMap<Integer, Integer>();//创建HashMap对象
        //加载声音文件,并且设置为1号声音放入hm中
        hm.put(1, sp.load(this, R.raw.a, 1));
        hm.put(2, sp.load(this, R.raw.b, 2));
    }
}

res目录下添加raw目录,raw添加所需要的音频文件。

编译运行即可。

结束!

相关推荐
阿巴斯甜17 小时前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android
Kapaseker18 小时前
实战 Compose 中的 IntrinsicSize
android·kotlin
xq952719 小时前
Andorid Google 登录接入文档
android
黄林晴20 小时前
告别 Modifier 地狱,Compose 样式系统要变天了
android·android jetpack
冬奇Lab1 天前
Android触摸事件分发、手势识别与输入优化实战
android·源码阅读
城东米粉儿1 天前
Android MediaPlayer 笔记
android
Jony_1 天前
Android 启动优化方案
android
阿巴斯甜1 天前
Android studio 报错:Cause: error=86, Bad CPU type in executable
android
张小潇1 天前
AOSP15 Input专题InputReader源码分析
android
_小马快跑_2 天前
Kotlin | 协程调度器选择:何时用CoroutineScope配置,何时用launch指定?
android