Android AudioTrack AudioRecord II
上一篇寫一半,我們把他完善了,針對AudioRecord的部份
new Thread(new Runnable() {
@Override
public void run() {
int recBuffSize=AudioRecord.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT);
//recBuffSize = 4096;//如果語音斷斷續續可以調整buffer size
AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT, recBuffSize);
byte[] buffer = new byte[recBuffSize];
audioRecord.startRecording(); // 开始录音
try {
clientSocket = new DatagramSocket();
} catch (SocketException e) {
e.printStackTrace();
}
InetAddress des = null; try { des = InetAddress.getByName("192.168.1.XX"); } catch (UnknownHostException e) { e.printStackTrace(); } int port = 3333; while (true) { int bufferReadResult = audioRecord.read(buffer, 0, recBuffSize); packet = new DatagramPacket(buffer, buffer.length, des, port); try { clientSocket.send(packet); } catch (Exception e) { Log.d("UDP SEND", "udp send data fail") } } audioRecord.stop(); audioRecord.release(); } }).start();
如果不編譯有問題,記得檢查是否有把權限打開在 AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET">
<uses-permission android:name="android.permission.WAKE_LOCK">
<uses-permission android:name="android.permission.RECORD_AUDIO">
android 8.0以上,要詢問使用者
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) ==PackageManager.PERMISSION_GRANTED) {
// put your code for Version>=Marshmallow
} else {
if (shouldShowRequestPermissionRationale(Manifest.permission.RECORD_AUDIO)) {
Toast.makeText(this,"App required access to audio", Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, 回傳碼);
}
上一篇AudioTrack的udp資接收就可以改成
byte[] receiveData = new byte[4096];
DatagramPacket packet = new DatagramPacket(receiveData, receiveData.length);
int port = 3333;
try {
serverSocket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
while (true) {
try {
serverSocket.receive(packet);
byte[] b = packet.getData();
audioTrack.write(b, 0, b.length);
} catch (Exception e) {
Log.d("UDP GET", "udp get data fail")
}
}
clientSocket = new DatagramSocket();
} catch (SocketException e) {
e.printStackTrace();
}
InetAddress des = null; try { des = InetAddress.getByName("192.168.1.XX"); } catch (UnknownHostException e) { e.printStackTrace(); } int port = 3333; while (true) { int bufferReadResult = audioRecord.read(buffer, 0, recBuffSize); packet = new DatagramPacket(buffer, buffer.length, des, port); try { clientSocket.send(packet); } catch (Exception e) { Log.d("UDP SEND", "udp send data fail") } } audioRecord.stop(); audioRecord.release(); } }).start();
留言
張貼留言