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

编译运行即可。

结束!

相关推荐
baidu_2474386112 小时前
Android ViewModel定时任务
android·开发语言·javascript
有位神秘人13 小时前
Android中Notification的使用详解
android·java·javascript
·云扬·13 小时前
MySQL Binlog落盘机制深度解析:性能与安全性的平衡艺术
android·mysql·adb
独自破碎E14 小时前
【BISHI9】田忌赛马
android·java·开发语言
代码s贝多芬的音符16 小时前
android 两个人脸对比 mlkit
android
darkb1rd17 小时前
五、PHP类型转换与类型安全
android·安全·php
gjxDaniel18 小时前
Kotlin编程语言入门与常见问题
android·开发语言·kotlin
csj5018 小时前
安卓基础之《(22)—高级控件(4)碎片Fragment》
android
峥嵘life19 小时前
Android16 【CTS】CtsMediaCodecTestCases等一些列Media测试存在Failed项
android·linux·学习
stevenzqzq19 小时前
Compose 中的状态可变性体系
android·compose