1. 程式人生 > >byte[]陣列播放wav格式音訊檔案

byte[]陣列播放wav格式音訊檔案

很多時候我們需要從伺服器上傳輸檔案,如果我們把音訊檔案轉成byte[]進行網路傳輸,然後再在客戶端進行播放,我們可以將byte[]生成音訊臨時檔案進行播放。

package com.djcken.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
import android.media.MediaPlayer;
import android.util.Log;

public class PlayWav {

	public static void PlayWav(Context context,byte[] byteWav)
	{
		try {  
	        File temp = File.createTempFile("KenTo", "wav", context.getCacheDir()); //生成臨時檔案
	        temp.deleteOnExit();  
	        FileOutputStream fos = new FileOutputStream(temp);  
	        fos.write(byteWav);  
	        fos.close();  
	        //播放音訊檔案
	        MediaPlayer mediaPlayer = new MediaPlayer();  
	        FileInputStream fis = new FileInputStream(temp);  
	        mediaPlayer.setDataSource(fis.getFD());  
	        mediaPlayer.prepare();  
	        mediaPlayer.start();  
	    } catch (IOException ex) {  
	        String string = ex.toString();  
	        Log.d("String", "string = " + string);
	        ex.printStackTrace();  
	    }  
	}
}