android 音频播放器,(一)SoundPool音频播放实例

1. Apk内,预定义按键与触发按键:

layout 按键定义:
    <Button
        android:id="@+id/start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="start"/>
    <Button
        android:id="@+id/pause"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="false"/>

按键触发,代码处理:
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start:
                playSound(1,3);
                break;
            case R.id.pause:
                mSoundpool.pause(1);
                mSoundpool.stop(1);
                break;
            default:
                break;
        }
    }

2. 创建SoundPool对象,与启动停止播放:

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

        initSp();
        start = (Button) findViewById(R.id.start);
        pause = (Button) findViewById(R.id.pause);

        start.setOnClickListener(this);
        pause.setOnClickListener(this);

    }
    
    private void initSp() {   // 初始化 mSoundpool     
        if (Build.VERSION.SDK_INT >= 21) {
            SoundPool.Builder builder = new SoundPool.Builder();
            builder.setMaxStreams(1);
            AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
            attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
            builder.setAudioAttributes(attrBuilder.build());
            mSoundpool = builder.build();
        } else {
            mSoundpool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
        }

            map = new HashMap();
            // 加载资源文件
            map.put(1, mSoundpool.load(this, R.raw.008, 1));
    }
    

    //  进行播放
    private void playSound(int sound, int number) {
    mSoundpool.play( sound, 
                 1,       // leftVolume
                 1,       // rightVolume
                 1,       // priority
                 number,  // loop
                (float)1);// rate,1为正常速度
    }


3. 按照,如上最简步骤进行调试,即可通过Soundpool类对象Api进行音频播放测试。 

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值