libstreaming 是一個開源的 Android 庫,用于實現實時流媒體傳輸
要使用 libstreaming 實現實時傳輸功能,你需要遵循以下步驟:
dependencies {
implementation 'net.majorkernelpanic.streaming:libstreaming:0.8.9'
}
<net.majorkernelpanic.streaming.gl.SurfaceView
android:id="@+id/surface_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
private Session mSession;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化 Session
mSession = new SessionBuilder()
.setContext(getApplicationContext())
.setAudioEncoder(SessionBuilder.AUDIO_AAC)
.setAudioQuality(new AudioQuality(8000, 16000))
.setVideoEncoder(SessionBuilder.VIDEO_H264)
.setVideoQuality(new VideoQuality(640, 480, 30, 1200000))
.setSurfaceView((SurfaceView) findViewById(R.id.surface_view))
.setPreviewOrientation(0)
.build();
}
private RtspServer mRtspServer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化 Session
// ...
// 初始化 RTSP 服務器
mRtspServer = new RtspServer();
mRtspServer.setPort(1234);
mRtspServer.setSession(mSession);
}
public void onStartButtonClick(View view) {
mSession.start();
mRtspServer.start();
}
public void onStopButtonClick(View view) {
mSession.stop();
mRtspServer.stop();
}
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
在運行時請求權限:
private static final int PERMISSION_REQUEST_CODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 請求權限
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO}, PERMISSION_REQUEST_CODE);
}
}
// 初始化 Session 和 RTSP 服務器
// ...
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED &&
grantResults[1] == PackageManager.PERMISSION_GRANTED) {
// 權限已獲得,可以繼續初始化 Session 和 RTSP 服務器
} else {
// 權限被拒絕,提示用戶并退出應用
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
finish();
}
}
}
完成以上步驟后,你就可以使用 libstreaming 實現實時傳輸功能了。你可以通過 VLC 播放器或其他支持 RTSP 協議的播放器觀看實時傳輸的視頻。