最近做一个播放音频的小功能,使用毛坯界面简单记录下(点击上边的ImageButton播放,下边的ImageView请无视)
activity_picture.xml页面:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<? 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" android:orientation = "vertical" tools:context = ".PictureActivity" > < ImageButton android:id = "@+id/ibCogVideo" android:layout_width = "100dp" android:layout_height = "100dp" android:src = "@mipmap/ic_launcher" /> < ImageView android:id = "@+id/ivCogPicture" android:layout_width = "300dp" android:layout_height = "300dp" android:layout_marginTop = "100dp" android:src = "@mipmap/ic_launcher" /> </ LinearLayout > |
PictureActivity.java页面:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
package com.example.two; import android.media.AudioManager; import android.media.SoundPool; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import java.util.HashMap; public class PictureActivity extends AppCompatActivity implements View.OnClickListener { private ImageButton ibCogVideo; private ImageView ivCogPicture; SoundPool mSoundPool; //一般用来播放短音频 HashMap<Integer,Integer> map= new HashMap<>(); //创建集合存放数据 @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_picture); initViews(); bindViews(); initDatas(); } /*初始化数据*/ private void initDatas() { mSoundPool= new SoundPool( 3 , AudioManager.STREAM_MUSIC, 0 ); //创建音频对象,参数为(可容纳音频个数,声音类型,音频品质默认为0) map.put( 1 ,mSoundPool.load( this ,R.raw.abc, 100 )); //设置第一个音频 } /*绑定点击事件*/ private void bindViews() { ibCogVideo.setOnClickListener( this ); } /*初始化控件*/ private void initViews() { ibCogVideo=findViewById(R.id.ibCogVideo); ivCogPicture=findViewById(R.id.ivCogPicture); } /*点击事件*/ @Override public void onClick(View v) { mSoundPool.play(map.get( 1 ), 1 , 1 , 100 , 0 , 1 ); //参数为(要播放的音频,左声道音量,右声道音量,音频优先级,循环次数,速率) } } |
另外,音频文件我放到了项目中,及res中的raw文件。貌似音频文件可以放入raw或者assets中,不同是raw一般放小型素材并且在代码中可以直接使用R.raw.xxx调用,而assets不可以。
AndroidStudio添加raw的方法:
点击OK,然后把音频文件拖入即可。
(get一个软件,可以使用格式工厂进行截取音频,超级方便!!!)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/hester_hester/article/details/89682025