本文實例講述了Android編程錄音工具類RecorderUtil定義與用法。分享給大家供大家參考,具體如下:
以下工具類都是經過實戰開發驗證都是可以直接復制使用的。
錄音工具類介紹:
錄音工具類主要平時用來開發語音聊天的,在微信和QQ上該工具類都是常用的,因為語音聊天。
使用硬件一般都要開權限,別忘了。這里還需要搭配 Android FileUtil 類使用,為了方便才這么封裝的
import android.media.MediaRecorder;import android.util.Log;import java.io.File;import java.io.IOException;import java.io.RandomAccessFile;/** * 錄音工具 */public class RecorderUtil { private static final String TAG = "RecorderUtil"; private String mFileName = null; private MediaRecorder mRecorder = null; private long startTime; private long timeInterval; private boolean isRecording; public RecorderUtil(){ mFileName = FileUtil.getCacheFilePath("tempAudio"); } /** * 開始錄音 */ public void startRecording() { if (mFileName == null) return; if (isRecording){ mRecorder.release(); mRecorder = null; } mRecorder = new MediaRecorder(); mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); mRecorder.setOutputFile(mFileName); mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); startTime = System.currentTimeMillis(); try { mRecorder.prepare(); mRecorder.start(); isRecording = true; } catch (Exception e){ Log.e(TAG, "prepare() failed"); } } /** * 停止錄音 */ public void stopRecording() { if (mFileName == null) return; timeInterval = System.currentTimeMillis() - startTime; try{ if (timeInterval>1000){ mRecorder.stop(); } mRecorder.release(); mRecorder = null; isRecording =false; }catch (Exception e){ Log.e(TAG, "release() failed"); } } /** * 取消語音 */ public synchronized void cancelRecording() { if (mRecorder != null) { try { mRecorder.release(); mRecorder = null; } catch (Exception e) { e.printStackTrace(); } File file = new File(mFileName); file.deleteOnExit(); } isRecording =false; } /** * 獲取錄音文件 */ public byte[] getDate() { if (mFileName == null) return null; try{ return readFile(new File(mFileName)); }catch (IOException e){ Log.e(TAG, "read file error" + e); return null; } } /** * 獲取錄音文件地址 */ public String getFilePath(){ return mFileName; } /** * 獲取錄音時長,單位秒 */ public long getTimeInterval() { return timeInterval/1000; } /** * 將文件轉化為byte[] * * @param file 輸入文件 */ private static byte[] readFile(File file) throws IOException { // Open file RandomAccessFile f = new RandomAccessFile(file, "r"); try { // Get and check length long longlength = f.length(); int length = (int) longlength; if (length != longlength) throw new IOException("File size >= 2 GB"); // Read file and return data byte[] data = new byte[length]; f.readFully(data); return data; } finally { f.close(); } }}使用步驟:
1. 首先private RecorderUtil recorder = new RecorderUtil(); 實例化一下
2. 開始錄音recorder.startRecording();
3. 錄音完成后停止錄音recorder.stopRecording();
4. 當然如果錄音開始之后想取消語音發送,類似于微信上滑取消語音發送,解決方案滑動監聽判斷確定取消發送,就不要將消息發出去并且還要調用recorder.cancelRecording(); //取消語音釋放資源 即可
希望本文所述對大家Android程序設計有所幫助。
新聞熱點
疑難解答