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添加所需要的音频文件。

编译运行即可。

结束!

相关推荐
百锦再4 小时前
第11章 泛型、trait与生命周期
android·网络·人工智能·python·golang·rust·go
会跑的兔子5 小时前
Android 16 Kotlin协程 第二部分
android·windows·kotlin
键来大师5 小时前
Android15 RK3588 修改默认不锁屏不休眠
android·java·framework·rk3588
江上清风山间明月8 小时前
Android 系统超级实用的分析调试命令
android·内存·调试·dumpsys
百锦再8 小时前
第12章 测试编写
android·java·开发语言·python·rust·go·erlang
用户693717500138412 小时前
Kotlin 协程基础入门系列:从概念到实战
android·后端·kotlin
SHEN_ZIYUAN12 小时前
Android 主线程性能优化实战:从 90% 降至 13%
android·cpu优化
曹绍华13 小时前
android 线程loop
android·java·开发语言
雨白13 小时前
Hilt 入门指南:从 DI 原理到核心用法
android·android jetpack
介一安全13 小时前
【Frida Android】实战篇3:基于 OkHttp 库的 Hook 抓包
android·okhttp·网络安全·frida