基本信息
源码名称:实时语音采集
源码大小:0.13M
文件格式:.7z
开发语言:Java
更新时间:2013-09-05
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
实时语音采集
package zyf.demo.moviedemo;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.InvalidParameterException;
import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import android.os.Bundle;
import android.os.Process;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;
import android.widget.Toast;
public class MovieRecorder extends Activity implements Callback, Runnable {
private String ip=null;
private SurfaceHolder mSurfaceHolder;
private boolean mMediaRecorderRecording = false;
private static Camera m_camera=null;
private CameraStreamer streamer = null;
private MediaPlayer mMediaPlayer=null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
InitSurfaceView();
InitMediaSharePreference();
streamer =new CameraStreamer();
}
private PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] _data, Camera _camera) {
// TODO Handle JPEG image data
/* onPictureTaken传入的第一个参数即为相片的byte */
Bitmap bm = BitmapFactory.decodeByteArray(_data, 0, _data.length);
File myCaptureFile = new File("/sdcard/1234566.jpg");
try {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(myCaptureFile));
/* 采用压缩转档方法 */
bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
/* 调用flush()方法,更新BufferStream */
bos.flush();
/* 结束OutputStream */
bos.close();
Log.e("","file length :" myCaptureFile.length());
int length =(int) myCaptureFile.length();
DataInputStream data_input= new DataInputStream(new FileInputStream(myCaptureFile));
byte [] buffer =new byte[length];
pic_data_output.write(intToByteArray(length));
int read =0,temp=0;
while(read<length)
{
temp= data_input.read(buffer, read, length-read);
if(temp==-1)
{
Log.e("", "no data get wait for data coming.....");
return;
}
read = temp;
}
pic_data_output.write(buffer,0, length);
pic_data_output.flush();
/* 将拍照下来且存储完毕的图文件,显示出来 */
// mImageView01.setImageBitmap(bm);
/* 显示完图文件,立即重置相机,并关闭预览 */
resetCamera();
pic_data_input.close();
pic_data_output.close();
cap_picture_fd.close();
} catch (Exception e) {
e.printStackTrace();
}
}
};
private void resetCamera()
{
if (m_camera != null )
{
m_camera.lock();
m_camera.stopPreview();
m_camera.release();
m_camera = null;
}
}
SharedPreferences mediaPreference;
private final String mediaShare = "media";
private void InitMediaSharePreference()
{
mediaPreference = this.getSharedPreferences(mediaShare, Context.MODE_PRIVATE);
}
LocalServerSocket lss =null;
LocalSocket receiver=null;
LocalSocket sender=null;
private void InitLocalSocket(){
try {
lss = new LocalServerSocket ("h264");
receiver = new LocalSocket ();
receiver.connect(new LocalSocketAddress("h264"));
receiver.setReceiveBufferSize(500000);
receiver.setSendBufferSize(500000);
sender = lss.accept();
sender.setReceiveBufferSize(500000);
sender.setSendBufferSize(500000);
} catch (IOException e) {
e.printStackTrace();
this.finish();
return;
}
}
LocalServerSocket lss2 =null;
LocalSocket receiver2=null;
LocalSocket sender2=null;
private SurfaceView mSurfaceView;
private void InitSurfaceView()
{
mSurfaceView = (SurfaceView)this.findViewById(R.id.surface_camera);
SurfaceHolder holder = mSurfaceView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height)
{
mSurfaceHolder = holder;
if(!mMediaRecorderRecording)
{
InitLocalSocket();
getSPSAndPPS();
if (!initializeVideo()) {
return;
}
startVideoRecording();
}
}
//get sps and pps if have record
private void getSPSAndPPS(){
StartMdatPlace = mediaPreference.getInt(
String.format("mdata_%d%d.mdat", videoWidth,videoHeight),
-1);
if(StartMdatPlace!=-1)
{
byte[] temp = new byte[100];
try {
FileInputStream file_in = VideoCameraActivity.this.openFileInput(
String.format("%d%d.sps", videoWidth,videoHeight));
int index = 0;
int read=0;
while(true)
{
read = file_in.read(temp,index,10);
if(read==-1) break;
else index = read;
}
Log.e("", "sps length:" index);
SPS = new byte[index];
System.arraycopy(temp, 0, SPS, 0, index);
file_in.close();
index =0;
//read PPS
file_in = VideoCameraActivity.this.openFileInput(
String.format("%d%d.pps", videoWidth,videoHeight));
while(true)
{
read = file_in.read(temp,index,10);
if(read==-1) break;
else index =read;
}
Log.e("", "pps length:" index);
PPS = new byte[index];
System.arraycopy(temp, 0, PPS, 0, index);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
SPS = null;
PPS = null;
}
}
public void surfaceCreated(SurfaceHolder holder)
{
mSurfaceHolder = holder;
}
public void surfaceDestroyed(SurfaceHolder holder)
{
releaseMediaRecorder();
if (data_output!=null) {
try {
data_output.close();
data_output=null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (client_fd != null) {
try {
client_fd.close();
client_fd=null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static MediaRecorder mMediaRecorder = null;
private int videoWidth = 320;
private int videoHeight = 240;
private int videoRate = 15;
private String fd = "data/data/com.android.getH264FormMediaRecorder/h264.3gp";
private boolean initializeVideo(){
if(mSurfaceHolder==null)
return false;
// TODO:get supported width and height
if (!init_streaming_socket()) {
return false;
}
mMediaRecorderRecording = true;
if(mMediaRecorder == null)
mMediaRecorder = new MediaRecorder ();
else
mMediaRecorder.reset();
try
{
m_camera = Camera.open();
} catch (RuntimeException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
m_camera.setDisplayOrientation(90);
m_camera.unlock();
mMediaRecorder.setCamera(m_camera);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mMediaRecorder.setVideoEncodingBitRate(1000);
mMediaRecorder.setVideoFrameRate(videoRate);
mMediaRecorder.setVideoSize(videoWidth, videoHeight);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
mMediaRecorder.setMaxDuration(0);
mMediaRecorder.setMaxFileSize(0);
if(SPS==null)
{
mMediaRecorder.setOutputFile(fd);
}
else
{
mMediaRecorder.setOutputFile(sender.getFileDescriptor());
}
try {
mMediaRecorder.prepare();
mMediaRecorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
releaseMediaRecorder();
}
return true;
}
private void startVideoRecording()
{
new Thread (streaming).start();
new Thread (picture_thread).start();
new Thread (voice_thread).start();
//new Thread (recv_voice_thread).start();
}
private Runnable voice_thread=new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Intent i=getIntent();
String ip=i.getStringExtra("ip");
//while (mMediaRecorderRecording) {
try {
streamer.setup(mSurfaceHolder,ip);
} catch (Exception e) {
// TODO: handle exception
Log.e("","error");
return;
}
streamer.start();
while (mMediaRecorderRecording)
{
;
}
//streamer.stop();
//}
}
};
private Runnable streaming = new Runnable()
{
public void run() {
try {
if(SPS == null)
{
Log.e("", "Rlease MediaRecorder and get SPS and PPS");
Thread.sleep(1000);
releaseMediaRecorder();
//first we must get sps and pps
findSpsPps();
initializeVideo();
}
DataInputStream dataInput = new DataInputStream (receiver.getInputStream());
//skip ftyp box and mdat box(decisbe by phone)
if(ReadSize(h264frame,StartMdatPlace,dataInput)==-1)
{
return ;
}
int h264head=21;
data_output.write(intToByteArray(h264head));
data_output.write(head);//4
data_output.write(SPS);//write sps 9
data_output.write(head);//4
data_output.write(PPS);//write pps 4
data_output.flush();
int h264length =0;
while(mMediaRecorderRecording)
{
h264length = dataInput.readInt();
byte [] oneframe =new byte [h264length];
if(ReadSize(oneframe,h264length,dataInput)==-1)
{
out_stream.close();
data_output.close();
client_fd.close();
return ;
}
//Log.e("", "h264length:" h264length);
int a_pix=h264length 4;
data_output.write(intToByteArray(a_pix));
data_output.write(head);
data_output.write(oneframe,0,h264length);
data_output.flush();
}
out_stream.close();
data_output.close();
client_fd.close();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
private Runnable recv_voice_thread =new Runnable() {
@Override
public void run() {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
// TODO Auto-generated method stub
while (!init_voice_socket()) {
show_message("初始化socket错误!");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
continue;
};
int iMinBufSize = AudioTrack.getMinBufferSize(8000,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT);
int buffer_size =16000;
AudioTrack m_out_trk = new AudioTrack(AudioManager.STREAM_MUSIC, 8000,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT,
iMinBufSize,
AudioTrack.MODE_STREAM);
byte []m_out_bytes=new byte[buffer_size];
int bytesRead=0,byteWrite=0;
int temp=0;
m_out_trk.play();
while (mMediaRecorderRecording) {
while(bytesRead<buffer_size)
{
try {
temp = data_input.read(m_out_bytes, temp, buffer_size-temp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bytesRead =temp;
}
temp=0;
while(byteWrite < m_out_bytes.length)
{
temp=m_out_trk.write(m_out_bytes, byteWrite,
m_out_bytes.length -byteWrite);
Log.e("", "h264length:" temp);
byteWrite =temp;
if (temp<iMinBufSize)
{
break;
}
}
bytesRead=0;
temp=0;
byteWrite =0;
m_out_trk.flush();
}
m_out_trk.stop();
m_out_trk.release();
m_out_trk=null;
try {
data_input.close();
in_stream.close();
voice_fd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private Runnable picture_thread = new Runnable()
{
public void run()
{
while (!init_capture_socket()) {
show_message("初始化socket错误!");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
continue;
};
int read =0,temp=0;
byte [] pic_head =new byte[]{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
while(read<8)
{
try {
temp= pic_data_input.read(pic_head, read, 8-read);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(temp==-1)
{
return;
}
read = temp;
}
mMediaRecorderRecording =true;
releaseMediaRecorder();
try
{
if (sender !=null) {
sender.close();
sender =null;
}
if (receiver !=null) {
receiver.close();
receiver =null;
}
if (lss !=null) {
lss.close();
lss =null;
}
}
catch (IOException e)
{
e.printStackTrace();
}
mMediaRecorderRecording=false;
streamer.stop();
try {
m_camera=Camera.open();
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Camera.Parameters parameters = m_camera.getParameters();
parameters.setPictureFormat(PixelFormat.JPEG);
parameters.setPreviewSize(320,240);
parameters.setPictureSize(2592, 1944);
m_camera.setParameters(parameters);
m_camera.autoFocus(null);
try {
m_camera.setPreviewDisplay(mSurfaceHolder);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
m_camera.setDisplayOrientation(90);
m_camera.startPreview();
m_camera.takePicture(null, null,null, jpegCallback);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
getSPSAndPPS();
InitLocalSocket();
initializeVideo();
startVideoRecording();
return ;
}
};
private void releaseMediaRecorder()
{
if(mMediaRecorder != null)
{
if(mMediaRecorderRecording)
{
mMediaRecorder.stop();
mMediaRecorderRecording = false;
}
mMediaRecorder.reset();
mMediaRecorder.release();
mMediaRecorder = null;
m_camera.lock();
if (m_camera!= null) {
m_camera.stopPreview();
m_camera.release();
m_camera = null;
}
}
}
private final int MAXFRAMEBUFFER = 20480*30;//*10;//20K
private byte[] h264frame = new byte[MAXFRAMEBUFFER];
private final byte[] head = new byte[]{0x00,0x00,0x00,0x01};
public void run() {
while (true) {
}
}
protected void onStop()
{
super.onStop();
try
{
if (sender !=null) {
sender.close();
sender =null;
}
if (receiver !=null) {
receiver.close();
receiver =null;
}
if (lss !=null) {
lss.close();
lss =null;
}
}
catch (IOException e)
{
e.printStackTrace();
}
mMediaRecorderRecording = false;
finish();
Process.killProcess(Process.myPid());
}
Socket client_fd=null;
OutputStream out_stream=null;
DataOutputStream data_output=null;
private boolean init_streaming_socket()
{
Intent i=getIntent();
ip=i.getStringExtra("ip");
try {
client_fd =new Socket(ip, 4322);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
show_message("无法连接到服务器!");
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
show_message("无法连接到服务器!");
return false;
}
try {
out_stream =client_fd.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
show_message("无法连接到服务器!");
return false;
}
// array_output= new ByteArrayOutputStream(20480*10);
data_output =new DataOutputStream(out_stream);
return true;
}
Socket cap_picture_fd=null;
DataOutputStream pic_data_output=null;
OutputStream pic_out_stream=null;
InputStream pic_in_stream=null;
DataInputStream pic_data_input=null;
private boolean init_capture_socket()
{
Intent i=getIntent();
ip=i.getStringExtra("ip");
try {
cap_picture_fd =new Socket(ip,8888);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
show_message("无法连接到服务器!");
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
show_message("无法连接到服务器!");
return false;
}
try {
pic_out_stream =cap_picture_fd.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
show_message("无法连接到服务器!");
return false;
}
try {
pic_in_stream = cap_picture_fd.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
show_message("无法连接到服务器!");
return false;
}
pic_data_output =new DataOutputStream(pic_out_stream);
pic_data_input =new DataInputStream(pic_in_stream);
return true;
}
private void show_message(String str)
{
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
Socket voice_fd=null;
InputStream in_stream=null;
DataInputStream data_input=null;
private boolean init_voice_socket()
{
Intent i=getIntent();
ip=i.getStringExtra("ip");
try {
voice_fd =new Socket(ip, 5005);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
show_message("无法连接到服务器!");
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
show_message("无法连接到服务器!");
return false;
}
try {
in_stream =voice_fd.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
show_message("无法连接到服务器!");
return false;
}
// array_output= new ByteArrayOutputStream(20480*10);
data_input =new DataInputStream(in_stream);
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
private byte[] SPS;
private byte[] PPS;
private int StartMdatPlace = 0;
private void findSpsPps() throws IOException
{
File file = new File (fd);
FileInputStream fileInput = new FileInputStream (file);
int length = (int)file.length();
byte[] data = new byte[length];
fileInput.read(data);
final byte[] mdat = new byte[]{0x6D,0x64,0x61,0x74};
final byte[] avcc = new byte[]{0x61,0x76,0x63,0x43};
//search from head
for(int i =0 ; i<100;i )//find StartMdatPlace
{
if(data[i] == mdat[0]&&data[i 1] == mdat[1] && data[i 2] == mdat[2] && data[i 3]==mdat[3])
{
StartMdatPlace = i 4;//find
break;
}
}
Log.e("", "StartMdatPlace:" StartMdatPlace);
String mdatStr = String.format("mdata_%d%d.mdat",videoWidth,videoHeight);
Editor editor = mediaPreference.edit();
editor.putInt(mdatStr,StartMdatPlace);
editor.commit();
//search from end
for(int i = length-1;i>0;i--)
{
if(data[i] == avcc[3] && data[i-1] == avcc[2] && data[i-2] == avcc[1] && data[i-3] == avcc[0])
{
//find avcc box
int sps_start = i 7;
byte[] sps_3gp = new byte[2];
sps_3gp[1] = data[sps_start];
sps_3gp[0] = data[sps_start 1];
// Log.e("", "0:" sps_3gp[0] "1:" sps_3gp[1]);
sps_start =2;//skip length
int sps_length = bytes2short(sps_3gp);
Log.e("", "SPS LENGTH:" sps_length);
SPS=new byte[sps_length];
System.arraycopy(data, sps_start, SPS, 0, sps_length);
//Save SPS
FileOutputStream file_out = VideoCameraActivity.this.openFileOutput(
String.format("%d%d.sps",videoWidth,videoHeight),
Context.MODE_PRIVATE);
file_out.write(SPS);
file_out.close();
int pps_start = sps_start sps_length 1;
byte[] pps_3gp =new byte[2];
pps_3gp[1] = data[pps_start];
pps_3gp[0] =data[pps_start 1];
int pps_length = bytes2short(pps_3gp);
Log.e("", "PPS LENGTH:" pps_length);
pps_start =2;
PPS = new byte[pps_length];
System.arraycopy(data, pps_start, PPS,0,pps_length);
//Save PPS
file_out = VideoCameraActivity.this.openFileOutput(
String.format("%d%d.pps",videoWidth,videoHeight),
Context.MODE_PRIVATE);
file_out.write(PPS);
file_out.close();
break;
}
}
}
public static byte[] intToByteArray(int i)
{
byte[] result = new byte[4];
result[0] = (byte)((i >> 24) & 0xFF);
result[1] = (byte)((i >> 16) & 0xFF);
result[2] = (byte)((i >> 8) & 0xFF);
result[3] = (byte)(i & 0xFF);
return result;
}
public short bytes2short(byte[] b)
{
short mask = 0xff;
short temp = 0;
short res = 0;
for (int i = 0; i < 2; i )
{
res <<= 8;
temp = (short) (b[1 - i] & mask);
res |= temp;
}
return res;
}
private int ReadSize(byte [] oneframe,int h264length, DataInputStream dataInput)
throws IOException, InterruptedException {
int read = 0;
int temp = 0;
while (read < h264length) {
temp = dataInput.read(oneframe, read, h264length - read);
if (temp == -1) {
Log.e("", "no data get wait for data coming.....");
return -1;
}
read = temp;
}
return 0;
}
}
实时语音采集
package zyf.demo.moviedemo;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.InvalidParameterException;
import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import android.os.Bundle;
import android.os.Process;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;
import android.widget.Toast;
public class MovieRecorder extends Activity implements Callback, Runnable {
private String ip=null;
private SurfaceHolder mSurfaceHolder;
private boolean mMediaRecorderRecording = false;
private static Camera m_camera=null;
private CameraStreamer streamer = null;
private MediaPlayer mMediaPlayer=null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
InitSurfaceView();
InitMediaSharePreference();
streamer =new CameraStreamer();
}
private PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] _data, Camera _camera) {
// TODO Handle JPEG image data
/* onPictureTaken传入的第一个参数即为相片的byte */
Bitmap bm = BitmapFactory.decodeByteArray(_data, 0, _data.length);
File myCaptureFile = new File("/sdcard/1234566.jpg");
try {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(myCaptureFile));
/* 采用压缩转档方法 */
bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
/* 调用flush()方法,更新BufferStream */
bos.flush();
/* 结束OutputStream */
bos.close();
Log.e("","file length :" myCaptureFile.length());
int length =(int) myCaptureFile.length();
DataInputStream data_input= new DataInputStream(new FileInputStream(myCaptureFile));
byte [] buffer =new byte[length];
pic_data_output.write(intToByteArray(length));
int read =0,temp=0;
while(read<length)
{
temp= data_input.read(buffer, read, length-read);
if(temp==-1)
{
Log.e("", "no data get wait for data coming.....");
return;
}
read = temp;
}
pic_data_output.write(buffer,0, length);
pic_data_output.flush();
/* 将拍照下来且存储完毕的图文件,显示出来 */
// mImageView01.setImageBitmap(bm);
/* 显示完图文件,立即重置相机,并关闭预览 */
resetCamera();
pic_data_input.close();
pic_data_output.close();
cap_picture_fd.close();
} catch (Exception e) {
e.printStackTrace();
}
}
};
private void resetCamera()
{
if (m_camera != null )
{
m_camera.lock();
m_camera.stopPreview();
m_camera.release();
m_camera = null;
}
}
SharedPreferences mediaPreference;
private final String mediaShare = "media";
private void InitMediaSharePreference()
{
mediaPreference = this.getSharedPreferences(mediaShare, Context.MODE_PRIVATE);
}
LocalServerSocket lss =null;
LocalSocket receiver=null;
LocalSocket sender=null;
private void InitLocalSocket(){
try {
lss = new LocalServerSocket ("h264");
receiver = new LocalSocket ();
receiver.connect(new LocalSocketAddress("h264"));
receiver.setReceiveBufferSize(500000);
receiver.setSendBufferSize(500000);
sender = lss.accept();
sender.setReceiveBufferSize(500000);
sender.setSendBufferSize(500000);
} catch (IOException e) {
e.printStackTrace();
this.finish();
return;
}
}
LocalServerSocket lss2 =null;
LocalSocket receiver2=null;
LocalSocket sender2=null;
private SurfaceView mSurfaceView;
private void InitSurfaceView()
{
mSurfaceView = (SurfaceView)this.findViewById(R.id.surface_camera);
SurfaceHolder holder = mSurfaceView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height)
{
mSurfaceHolder = holder;
if(!mMediaRecorderRecording)
{
InitLocalSocket();
getSPSAndPPS();
if (!initializeVideo()) {
return;
}
startVideoRecording();
}
}
//get sps and pps if have record
private void getSPSAndPPS(){
StartMdatPlace = mediaPreference.getInt(
String.format("mdata_%d%d.mdat", videoWidth,videoHeight),
-1);
if(StartMdatPlace!=-1)
{
byte[] temp = new byte[100];
try {
FileInputStream file_in = VideoCameraActivity.this.openFileInput(
String.format("%d%d.sps", videoWidth,videoHeight));
int index = 0;
int read=0;
while(true)
{
read = file_in.read(temp,index,10);
if(read==-1) break;
else index = read;
}
Log.e("", "sps length:" index);
SPS = new byte[index];
System.arraycopy(temp, 0, SPS, 0, index);
file_in.close();
index =0;
//read PPS
file_in = VideoCameraActivity.this.openFileInput(
String.format("%d%d.pps", videoWidth,videoHeight));
while(true)
{
read = file_in.read(temp,index,10);
if(read==-1) break;
else index =read;
}
Log.e("", "pps length:" index);
PPS = new byte[index];
System.arraycopy(temp, 0, PPS, 0, index);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
SPS = null;
PPS = null;
}
}
public void surfaceCreated(SurfaceHolder holder)
{
mSurfaceHolder = holder;
}
public void surfaceDestroyed(SurfaceHolder holder)
{
releaseMediaRecorder();
if (data_output!=null) {
try {
data_output.close();
data_output=null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (client_fd != null) {
try {
client_fd.close();
client_fd=null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static MediaRecorder mMediaRecorder = null;
private int videoWidth = 320;
private int videoHeight = 240;
private int videoRate = 15;
private String fd = "data/data/com.android.getH264FormMediaRecorder/h264.3gp";
private boolean initializeVideo(){
if(mSurfaceHolder==null)
return false;
// TODO:get supported width and height
if (!init_streaming_socket()) {
return false;
}
mMediaRecorderRecording = true;
if(mMediaRecorder == null)
mMediaRecorder = new MediaRecorder ();
else
mMediaRecorder.reset();
try
{
m_camera = Camera.open();
} catch (RuntimeException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
m_camera.setDisplayOrientation(90);
m_camera.unlock();
mMediaRecorder.setCamera(m_camera);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mMediaRecorder.setVideoEncodingBitRate(1000);
mMediaRecorder.setVideoFrameRate(videoRate);
mMediaRecorder.setVideoSize(videoWidth, videoHeight);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
mMediaRecorder.setMaxDuration(0);
mMediaRecorder.setMaxFileSize(0);
if(SPS==null)
{
mMediaRecorder.setOutputFile(fd);
}
else
{
mMediaRecorder.setOutputFile(sender.getFileDescriptor());
}
try {
mMediaRecorder.prepare();
mMediaRecorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
releaseMediaRecorder();
}
return true;
}
private void startVideoRecording()
{
new Thread (streaming).start();
new Thread (picture_thread).start();
new Thread (voice_thread).start();
//new Thread (recv_voice_thread).start();
}
private Runnable voice_thread=new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Intent i=getIntent();
String ip=i.getStringExtra("ip");
//while (mMediaRecorderRecording) {
try {
streamer.setup(mSurfaceHolder,ip);
} catch (Exception e) {
// TODO: handle exception
Log.e("","error");
return;
}
streamer.start();
while (mMediaRecorderRecording)
{
;
}
//streamer.stop();
//}
}
};
private Runnable streaming = new Runnable()
{
public void run() {
try {
if(SPS == null)
{
Log.e("", "Rlease MediaRecorder and get SPS and PPS");
Thread.sleep(1000);
releaseMediaRecorder();
//first we must get sps and pps
findSpsPps();
initializeVideo();
}
DataInputStream dataInput = new DataInputStream (receiver.getInputStream());
//skip ftyp box and mdat box(decisbe by phone)
if(ReadSize(h264frame,StartMdatPlace,dataInput)==-1)
{
return ;
}
int h264head=21;
data_output.write(intToByteArray(h264head));
data_output.write(head);//4
data_output.write(SPS);//write sps 9
data_output.write(head);//4
data_output.write(PPS);//write pps 4
data_output.flush();
int h264length =0;
while(mMediaRecorderRecording)
{
h264length = dataInput.readInt();
byte [] oneframe =new byte [h264length];
if(ReadSize(oneframe,h264length,dataInput)==-1)
{
out_stream.close();
data_output.close();
client_fd.close();
return ;
}
//Log.e("", "h264length:" h264length);
int a_pix=h264length 4;
data_output.write(intToByteArray(a_pix));
data_output.write(head);
data_output.write(oneframe,0,h264length);
data_output.flush();
}
out_stream.close();
data_output.close();
client_fd.close();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
private Runnable recv_voice_thread =new Runnable() {
@Override
public void run() {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
// TODO Auto-generated method stub
while (!init_voice_socket()) {
show_message("初始化socket错误!");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
continue;
};
int iMinBufSize = AudioTrack.getMinBufferSize(8000,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT);
int buffer_size =16000;
AudioTrack m_out_trk = new AudioTrack(AudioManager.STREAM_MUSIC, 8000,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT,
iMinBufSize,
AudioTrack.MODE_STREAM);
byte []m_out_bytes=new byte[buffer_size];
int bytesRead=0,byteWrite=0;
int temp=0;
m_out_trk.play();
while (mMediaRecorderRecording) {
while(bytesRead<buffer_size)
{
try {
temp = data_input.read(m_out_bytes, temp, buffer_size-temp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bytesRead =temp;
}
temp=0;
while(byteWrite < m_out_bytes.length)
{
temp=m_out_trk.write(m_out_bytes, byteWrite,
m_out_bytes.length -byteWrite);
Log.e("", "h264length:" temp);
byteWrite =temp;
if (temp<iMinBufSize)
{
break;
}
}
bytesRead=0;
temp=0;
byteWrite =0;
m_out_trk.flush();
}
m_out_trk.stop();
m_out_trk.release();
m_out_trk=null;
try {
data_input.close();
in_stream.close();
voice_fd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private Runnable picture_thread = new Runnable()
{
public void run()
{
while (!init_capture_socket()) {
show_message("初始化socket错误!");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
continue;
};
int read =0,temp=0;
byte [] pic_head =new byte[]{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
while(read<8)
{
try {
temp= pic_data_input.read(pic_head, read, 8-read);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(temp==-1)
{
return;
}
read = temp;
}
mMediaRecorderRecording =true;
releaseMediaRecorder();
try
{
if (sender !=null) {
sender.close();
sender =null;
}
if (receiver !=null) {
receiver.close();
receiver =null;
}
if (lss !=null) {
lss.close();
lss =null;
}
}
catch (IOException e)
{
e.printStackTrace();
}
mMediaRecorderRecording=false;
streamer.stop();
try {
m_camera=Camera.open();
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Camera.Parameters parameters = m_camera.getParameters();
parameters.setPictureFormat(PixelFormat.JPEG);
parameters.setPreviewSize(320,240);
parameters.setPictureSize(2592, 1944);
m_camera.setParameters(parameters);
m_camera.autoFocus(null);
try {
m_camera.setPreviewDisplay(mSurfaceHolder);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
m_camera.setDisplayOrientation(90);
m_camera.startPreview();
m_camera.takePicture(null, null,null, jpegCallback);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
getSPSAndPPS();
InitLocalSocket();
initializeVideo();
startVideoRecording();
return ;
}
};
private void releaseMediaRecorder()
{
if(mMediaRecorder != null)
{
if(mMediaRecorderRecording)
{
mMediaRecorder.stop();
mMediaRecorderRecording = false;
}
mMediaRecorder.reset();
mMediaRecorder.release();
mMediaRecorder = null;
m_camera.lock();
if (m_camera!= null) {
m_camera.stopPreview();
m_camera.release();
m_camera = null;
}
}
}
private final int MAXFRAMEBUFFER = 20480*30;//*10;//20K
private byte[] h264frame = new byte[MAXFRAMEBUFFER];
private final byte[] head = new byte[]{0x00,0x00,0x00,0x01};
public void run() {
while (true) {
}
}
protected void onStop()
{
super.onStop();
try
{
if (sender !=null) {
sender.close();
sender =null;
}
if (receiver !=null) {
receiver.close();
receiver =null;
}
if (lss !=null) {
lss.close();
lss =null;
}
}
catch (IOException e)
{
e.printStackTrace();
}
mMediaRecorderRecording = false;
finish();
Process.killProcess(Process.myPid());
}
Socket client_fd=null;
OutputStream out_stream=null;
DataOutputStream data_output=null;
private boolean init_streaming_socket()
{
Intent i=getIntent();
ip=i.getStringExtra("ip");
try {
client_fd =new Socket(ip, 4322);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
show_message("无法连接到服务器!");
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
show_message("无法连接到服务器!");
return false;
}
try {
out_stream =client_fd.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
show_message("无法连接到服务器!");
return false;
}
// array_output= new ByteArrayOutputStream(20480*10);
data_output =new DataOutputStream(out_stream);
return true;
}
Socket cap_picture_fd=null;
DataOutputStream pic_data_output=null;
OutputStream pic_out_stream=null;
InputStream pic_in_stream=null;
DataInputStream pic_data_input=null;
private boolean init_capture_socket()
{
Intent i=getIntent();
ip=i.getStringExtra("ip");
try {
cap_picture_fd =new Socket(ip,8888);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
show_message("无法连接到服务器!");
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
show_message("无法连接到服务器!");
return false;
}
try {
pic_out_stream =cap_picture_fd.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
show_message("无法连接到服务器!");
return false;
}
try {
pic_in_stream = cap_picture_fd.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
show_message("无法连接到服务器!");
return false;
}
pic_data_output =new DataOutputStream(pic_out_stream);
pic_data_input =new DataInputStream(pic_in_stream);
return true;
}
private void show_message(String str)
{
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
Socket voice_fd=null;
InputStream in_stream=null;
DataInputStream data_input=null;
private boolean init_voice_socket()
{
Intent i=getIntent();
ip=i.getStringExtra("ip");
try {
voice_fd =new Socket(ip, 5005);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
show_message("无法连接到服务器!");
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
show_message("无法连接到服务器!");
return false;
}
try {
in_stream =voice_fd.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
show_message("无法连接到服务器!");
return false;
}
// array_output= new ByteArrayOutputStream(20480*10);
data_input =new DataInputStream(in_stream);
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
private byte[] SPS;
private byte[] PPS;
private int StartMdatPlace = 0;
private void findSpsPps() throws IOException
{
File file = new File (fd);
FileInputStream fileInput = new FileInputStream (file);
int length = (int)file.length();
byte[] data = new byte[length];
fileInput.read(data);
final byte[] mdat = new byte[]{0x6D,0x64,0x61,0x74};
final byte[] avcc = new byte[]{0x61,0x76,0x63,0x43};
//search from head
for(int i =0 ; i<100;i )//find StartMdatPlace
{
if(data[i] == mdat[0]&&data[i 1] == mdat[1] && data[i 2] == mdat[2] && data[i 3]==mdat[3])
{
StartMdatPlace = i 4;//find
break;
}
}
Log.e("", "StartMdatPlace:" StartMdatPlace);
String mdatStr = String.format("mdata_%d%d.mdat",videoWidth,videoHeight);
Editor editor = mediaPreference.edit();
editor.putInt(mdatStr,StartMdatPlace);
editor.commit();
//search from end
for(int i = length-1;i>0;i--)
{
if(data[i] == avcc[3] && data[i-1] == avcc[2] && data[i-2] == avcc[1] && data[i-3] == avcc[0])
{
//find avcc box
int sps_start = i 7;
byte[] sps_3gp = new byte[2];
sps_3gp[1] = data[sps_start];
sps_3gp[0] = data[sps_start 1];
// Log.e("", "0:" sps_3gp[0] "1:" sps_3gp[1]);
sps_start =2;//skip length
int sps_length = bytes2short(sps_3gp);
Log.e("", "SPS LENGTH:" sps_length);
SPS=new byte[sps_length];
System.arraycopy(data, sps_start, SPS, 0, sps_length);
//Save SPS
FileOutputStream file_out = VideoCameraActivity.this.openFileOutput(
String.format("%d%d.sps",videoWidth,videoHeight),
Context.MODE_PRIVATE);
file_out.write(SPS);
file_out.close();
int pps_start = sps_start sps_length 1;
byte[] pps_3gp =new byte[2];
pps_3gp[1] = data[pps_start];
pps_3gp[0] =data[pps_start 1];
int pps_length = bytes2short(pps_3gp);
Log.e("", "PPS LENGTH:" pps_length);
pps_start =2;
PPS = new byte[pps_length];
System.arraycopy(data, pps_start, PPS,0,pps_length);
//Save PPS
file_out = VideoCameraActivity.this.openFileOutput(
String.format("%d%d.pps",videoWidth,videoHeight),
Context.MODE_PRIVATE);
file_out.write(PPS);
file_out.close();
break;
}
}
}
public static byte[] intToByteArray(int i)
{
byte[] result = new byte[4];
result[0] = (byte)((i >> 24) & 0xFF);
result[1] = (byte)((i >> 16) & 0xFF);
result[2] = (byte)((i >> 8) & 0xFF);
result[3] = (byte)(i & 0xFF);
return result;
}
public short bytes2short(byte[] b)
{
short mask = 0xff;
short temp = 0;
short res = 0;
for (int i = 0; i < 2; i )
{
res <<= 8;
temp = (short) (b[1 - i] & mask);
res |= temp;
}
return res;
}
private int ReadSize(byte [] oneframe,int h264length, DataInputStream dataInput)
throws IOException, InterruptedException {
int read = 0;
int temp = 0;
while (read < h264length) {
temp = dataInput.read(oneframe, read, h264length - read);
if (temp == -1) {
Log.e("", "no data get wait for data coming.....");
return -1;
}
read = temp;
}
return 0;
}
}