zoukankan      html  css  js  c++  java
  • SoundPool播放简短音乐文件

    开发Android应用中我们可能经常需要播放多媒体声音文件,一般使用MediaPlayer类,但该类占用资源较多,对于游戏等应用可能不是很适合,SoundPool类在SDK的android.media.SoundPool,顾名思义是声音池的意思。主要播放一些较短的声音片段,可以从程序的资源或文件系统加载,相对于MediaPlayer类可以做到使用较少的CPU资源和较短的反应延迟。SoundPool和其他声音播放类相比,其特点是可以自行设置声音的品质、音量、播放比率等参等。并且它可以同时管理多个音频流,每个流都有独自的ID,对某个音频流的管理都是通过ID进行的。
             SoundPool基本使用方法:
    1. 创建一个SoundPool 
    创建一个SoundPool对象:new SoundPool(int maxStreams, int streamType, int srcQuality)
    public SoundPool(int maxStream, int streamType, int srcQuality) 
    maxStream —— 同时播放的流的最大数量 
    streamType —— 流的类型,一般为STREAM_MUSIC(具体在AudioManager类中列出) 
    srcQuality —— 采样率转化质量,当前无效果,使用0作为默认值 
    eg. 
    SoundPool soundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
    创建了一个最多支持3个流同时播放的,类型标记为音乐的SoundPool。
    2、 从资源或者文件载入音频流: load(Context context, int resId, int priority);
    soundpool的加载: 
    int  load(Context context, int resId, int priority)  //从APK资源载入 
    int  load(FileDescriptor fd, long offset, long length, int priority)  //从FileDescriptor对象载入 
    int  load(AssetFileDescriptor afd, int priority)  //从Asset对象载入 
    int  load(String path, int priority)  //从完整文件路径名载入 
    最后一个参数为优先级。
    一般把多个声音放到HashMap中去,比如 
    soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100); 
    soundPoolMap = new HashMap<Integer, Integer>();   
    soundPoolMap.put(1, soundPool.load(this, R.raw.dingdong, 1));
    3、  播放声音play (int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate);
    play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate) ,
    其中leftVolume和rightVolume表示左右音量,
    priority表示优先级,
    loop表示循环次数,
    rate表示速率,如  //速率最低0.5最高为2,1代表正常速度 
    sp.play(soundId, 1, 1, 0, 0, 1); 
    而停止则可以使用 pause(int streamID) 方法,这里的streamID和soundID均在构造SoundPool类的
    第一个参数中指明了总数量,而id从0开始。
    注意事项:
       1. SoundPool最大只能申请1M的内存空间,这就意味着我们只能用一些很短的声音片段,而不是用它来播放歌曲或者做游戏背景音乐。
       2. SoundPool提供了pause和stop方法,但这些方法建议最好不要轻易使用,因为有些时候它们可能会使你的程序莫名其妙的终止。Android开发网建议使用这两个方法的时候尽可能多做测试工作,还有些朋友反映它们不会立即中止播放声音,而是把缓冲区里的数据播放完才会停下来,也许会多播放一秒钟。

       3. SoundPool的效率问题。其实SoundPool的效率在这些播放类中算是很好的了,这可能会影响用户体验。也许这不能管SoundPool本身,因为到了性能比较好的Droid中这个延迟就可以让人接受了。

     4. 有的文件虽然很小,但是解码出来为16位的PCM可能会超过1M的空间这时只能播放很短的部分声音。文件超过1M的就播不了了。

    下面直接上代码


    布局文件

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/LinearLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity" >
    	<Button 
    	    android:id="@+id/StartButton"
    	    android:layout_width="match_parent"
    	    android:layout_height="wrap_content"
    	    android:text="开始播放"
    	    />
    	<Button
    	    android:id="@+id/PauseButton"
    	    android:layout_width="match_parent"
    	    android:layout_height="wrap_content"
    	    android:text="暂停播放" />
    	<Button
    	    android:id="@+id/StopButton"
    	    android:layout_width="match_parent"
    	    android:layout_height="wrap_content"
    	    android:text="停止播放" />
    
    </LinearLayout>

    源代码

    package com.example.testsoundpool;
    
    import java.util.HashMap;
    
    import android.R.bool;
    import android.media.AudioManager;
    import android.media.SoundPool;
    import android.media.SoundPool.OnLoadCompleteListener;
    import android.os.Bundle;
    import android.app.Activity;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    
    public class MainActivity extends Activity implements OnClickListener{
    
    	private SoundPool sp=null;//声明一个SoundPool的引用
    	private HashMap <Integer,Integer> hm;//声明一个HashMap来存放声音资源
    	private int currentStreamId;//当前播放的StreamId
    	private Button startPlayButton;//播放按钮
    	private Button PausePlayButton;//暂停按钮
    	private Button stopPlayButton;//停止播放
    	private Boolean isFinishedLoad=false;//查看音乐文件是否加载完毕
    	private Boolean isPausePlay=false;//是否暂停播放
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		//按钮点击响应函数
    		startPlayButton=(Button)findViewById(R.id.StartButton);
    		PausePlayButton=(Button)findViewById(R.id.PauseButton);
    		stopPlayButton=(Button)findViewById(R.id.StopButton);
    		startPlayButton.setOnClickListener(this);
    		PausePlayButton.setOnClickListener(this);
    		stopPlayButton.setOnClickListener(this);
    		//初始化SoundPool
    		initSoundPool();
    	}
    
    	@Override
    	public boolean onCreateOptionsMenu(Menu menu) {
    		// Inflate the menu; this adds items to the action bar if it is present.
    		getMenuInflater().inflate(R.menu.activity_main, menu);
    		return true;
    	}
    
    	//按钮响应函数
    	@Override
    	public void onClick(View v) {
    		// TODO Auto-generated method stub
    		switch(v.getId()){
    		case R.id.StartButton:
    			playSound(1,0);//播放dudu,dudu文件被解码为16位的PCM数据后超过了SoundPool的1M缓冲区了,循环不了,而且不能播完整个歌曲
    			//playSound(2,-1);//循环播放musictest
    			break;
    		case R.id.PauseButton:
    			isPausePlay=true;
    			sp.pause(currentStreamId);
    			break;
    		case R.id.StopButton:
    			isPausePlay=false;
    			sp.stop(currentStreamId);
    			break;
    		default:
    			System.out.println("switch default");
    			break;
    		}
    	}
    	
    	public void initSoundPool(){
    		System.out.println("+initSoundPool+");
    		sp=new SoundPool(4,AudioManager.STREAM_MUSIC,0);//创建SoundPool对象
    		sp.setOnLoadCompleteListener(new OnLoadCompleteListener() {
    			
    			@Override
    			public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
    				// TODO Auto-generated method stub
    				isFinishedLoad=true;
    				System.out.println("setOnLoadCompleteListener");
    			}
    		});
    		hm=new HashMap<Integer,Integer>();//创建HashMap对象
    		hm.put(1, sp.load(this, R.raw.dudu, 0));//加载dudu声音文件并设置为1号文件放入hm
    		hm.put(2, sp.load(this, R.raw.musictest, 0));//加载musictest声音文件并设置为2号文件放入hm
    		System.out.println("-initSoundPool-");
    	}
    	
    	//sound hm中的第几个歌曲
    	//loop 是否循环 0不循环 -1循环
    	public void playSound(int sound,int loop){
    		String log;
    		if(!isPausePlay){
    			AudioManager am=(AudioManager)this.getSystemService(AUDIO_SERVICE);
    			float currentStreamVolume=am.getStreamVolume(AudioManager.STREAM_MUSIC);
    			float maxStreamVolume=am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    			float setVolume=(float)currentStreamVolume/maxStreamVolume;
    			if(isFinishedLoad)
    				currentStreamId=sp.play(hm.get(sound), setVolume, setVolume, 1, loop, 1.0f);
    			log="playSound currentStreamId:"+String.valueOf(currentStreamId);
    			System.out.println(log);
    		}
    		else{
    			isPausePlay=false;
    			sp.resume(currentStreamId);
    		}
    	}
    	
    	@Override
    	protected void onDestroy() {
    		// TODO Auto-generated method stub
    		super.onDestroy();
    		sp.unload(currentStreamId);
    		sp.release();
    	}
    }


    源代码下载地址

  • 相关阅读:
    设计模式入门
    Spring Boot 日志
    Spring Boot入门
    Vue--过滤器、指令、插件
    CentOS7更换yum源
    CentOS7中修改运行级别
    Xshell进行远程登录
    Linux的目录结构详情
    通过VMware Tools配置Centos7与本地主机的共享文件夹(亲测)
    eclipse中的Git操作
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3091780.html
Copyright © 2011-2022 走看看