Android RTP (Video & Audio Stream via VLC Player)

In this tutorial, you’ll learn how to use Android Studio to start Android RTP project development. You will learn the following:

  • How to use Android Studio to create a native project.
  • How to use RTP in android project.

Download the required software packages

Open Android Studio.

Start a new Android Studio project

Start a new Android Studio project

Select Start a new Android Studio project. Enter your custom Application name, Company Domain and select Project location. Click Next.

Configure your new project.

Configure your new project.

Select Phone and Tablet. Make sure API 15 selected. Click Next.

Configure your new project.

Configure your new project.

Select Empty Activity and click Next.

Add an activity to Mobile.

Add an activity to Mobile.

Click Finish.

Customize the activity.

Customize the activity.

Import the libstreaming library (https://github.com/fyhertz/libstreaming) to Android Studio you can try this:

  • Open your project in Android Studio.
  • Download the library (using Git, or a zip archive to unzip).

Select File > New > Import Module.

New Module.

New Module.

Select library libstreaming source directory and click Next.

New Module.

New Module.

Click Finish.

New Module.

New Module.

On the root of your project directory create/modify the settings.gradle file. It should contain something like the following:

include 'app', ':libstreaming'
  • Gradle clean & build/close the project and reopen/re-import it.
  • Edit your project’s build.gradle to add this in the “depencies” section:
dependencies {
     //...
        compile project(':libstreaming')
     }

Open the MainActivity.java and replace with this code

package my.intellij.androidrtp;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.Window;
import android.view.WindowManager;

import net.majorkernelpanic.streaming.Session;
import net.majorkernelpanic.streaming.SessionBuilder;
import net.majorkernelpanic.streaming.audio.AudioQuality;
import net.majorkernelpanic.streaming.gl.SurfaceView;
import net.majorkernelpanic.streaming.rtsp.RtspServer;

/**
 * A straightforward example of how to use the RTSP server included in libstreaming.
 */
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, RtspServer.CallbackListener, Session.Callback{

    private final static String TAG = "MainActivity";

    private SurfaceView mSurfaceView;
    private  Session mSession;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.activity_main);

        mSurfaceView = (SurfaceView) findViewById(R.id.surface);

        
        // Sets the port of the RTSP server to 1234
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
        editor.putString(  RtspServer.KEY_PORT, String.valueOf(1234));
        editor.commit();



        // Configures the SessionBuilder
        mSession =  SessionBuilder.getInstance()
                .setCallback(this)
                .setSurfaceView((net.majorkernelpanic.streaming.gl.SurfaceView) mSurfaceView)
                .setPreviewOrientation(90)
                .setContext(getApplicationContext())
                .setAudioEncoder(SessionBuilder.AUDIO_AAC)
                .setAudioQuality(new AudioQuality(8000, 16000))
                .setVideoEncoder(SessionBuilder.VIDEO_H264)
                //.setVideoQuality(new VideoQuality(320,240,20,500000))
                .build();

        mSurfaceView.getHolder().addCallback(this);

        ((net.majorkernelpanic.streaming.gl.SurfaceView) mSurfaceView).setAspectRatioMode(net.majorkernelpanic.streaming.gl.SurfaceView.ASPECT_RATIO_PREVIEW);
        String ip, port, path;

        // Starts the RTSP server
        this.startService(new Intent(this,RtspServer.class));

        Log.d("test", "1");



        mSession.startPreview(); //camera preview on phone surface
        mSession.start();

    }

    @Override
    public void onResume()
    {
        super.onResume();
        mSession.stopPreview();
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        mSession.release();
        mSurfaceView.getHolder().removeCallback(this);
    }

    //region   ----------------------------------implement methods required
    @Override
    public void onError(RtspServer server, Exception e, int error) {
        Log.e("Server", e.toString());
    }

    @Override
    public void onMessage(RtspServer server, int message) {
        Log.e("Server", "unkown message");
    }

    @Override
    public void onBitrateUpdate(long bitrate) {

    }

    @Override
    public void onSessionError(int reason, int streamType, Exception e) {

    }

    @Override
    public void onPreviewStarted() {

    }

    @Override
    public void onSessionConfigured() {

    }

    @Override
    public void onSessionStarted() {

    }

    @Override
    public void onSessionStopped() {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    //endregion
}

Open activity_main.xml in app > res > layout and replace with this code.

<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="my.intellij.androidrtp.MainActivity" android:color="@android:color/background_light">

    <net.majorkernelpanic.streaming.gl.SurfaceView android:id="@+id/surface" android:layout_width="match_parent" android:layout_height="match_parent" />

</RelativeLayout>

Open AndroidManifest.xml and replace with this code.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="my.intellij.androidrtp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name="net.majorkernelpanic.streaming.rtsp.RtspServer" />
    </application>

    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

</manifest>

Build and run the Android rtp sender app. Now start the vlc player and click Media > Open Network Stream menu. Enter the following url (please update with your android ip) and click play button.

rtsp://192.168.0.113:1234

Open Network.

Open Network.

How to create a c++ library with NDK on Android Studio

In this tutorial, you’ll learn how to use Android Studio to start Android NDK project development. You will learn the following:

  • How to use Android Studio to create a native project.
  • How to build and trace native code.

Download the required software packages

Open Android Studio.

Start a new Android Studio project

Start a new Android Studio project

Select Start a new Android Studio project. Enter your custom Application name, Company Domain and select Project location. Click Next.

New Project

New Project

Select Phone and Tablet. Make sure API 15 selected. Click Next.

Configure your new project.

Configure your new project.

Click Next.

Configure your new project

Configure your new project

Select Black Activity and click Next.

Configure your new project

Configure your new project

Click Finish.

Customize the Activity.

Customize the Activity.

Select the menu File > Project Structure > SDK Location and set Android NDK Location.

Project Structure

Project Structure

Add new code inside defaultConfig block.

defaultConfig {
        applicationId "my.intellij.androidrtp"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        ndk {
            moduleName "hello-android-jni"
        }
}

Add JNI function and load jni shared lib into project. Select Android Studio Project pane > app > java > my.intellij.androidrtp > MainActivity, and add JNI function getMsgFromJni() and System.loadLibrary() to the end of class MainActivity.

static {
        System.loadLibrary("hello-android-jni");
    }
    public native String getMsgFromJni();

Configure javah. Select Android Studio > Preferences > Tools > External Tools. Click + symbol.

Create Tool for javah.

Create Tool for javah.

Configure ndk-build.

Create Tool for ndk-build.

Create Tool for ndk-build.

Configure ndk-build clean.

Create Tool for ndk-build clean.

Create Tool for ndk-build clean.

Click Ok.

Preferences.

Preferences.

Configure build.gradle to setup JNI folder location. Open build.gradle file and place this code into android block.

android {
    compileSdkVersion 24
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "my.intellij.androidrtp"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        ndk {
            moduleName "hello-android-jni"
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    sourceSets.main {
        jni.srcDirs = [] 
        jniLibs.srcDirs=['libs']
    }

}

Let’s add one line in ‘gradle.properties’.

android.useDeprecatedNdk=true

Build the project. Select MainActivity, NDK > javah.

NDK javah

NDK javah

Switch to project mode and select NewC/C++ Source File.

C/C++ Source File

C/C++ Source File

Name it as hello-android-jni and click Ok.

Create New C/C++ Source File

Create New C/C++ Source File

Replace with this code in hello-android-jni.cpp.

#include "my_intellij_androidrtp_MainActivity.h"

JNIEXPORT jstring JNICALL Java_my_intellij_androidrtp_MainActivity_getMsgFromJni(JNIEnv *, jobject){

    return (*env)->NewStringUTF(env, "Hello From Jni");
}

Create some MakeFiles. Select jni folder > New > File.

Create some MakeFiles

Create some MakeFiles

Name it as Android.mk. Click Ok.

Create some MakeFiles

Create some MakeFiles

Click Ok.

Register New File Type Association

Register New File Type Association

Repeat same process to create Application.mk file. Replace both files with these codes.

Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE		:= hello-android-jni
LOCAL_SRC_FILES		:= hello-android-jni.cpp
include $(BUILD_SHARED_LIBRARY)

Application.mk

APP_MODULES := hello-android-jni

APP_ABI := all

Build NDK Library. Select jni folder > NDK > ndk-build.

Build NDK Library

Build NDK Library

Success message.

Build NDK Library

Build NDK Library

Replace MainActivity.java with this code.

package my.intellij.androidrtp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.i("MyTag", getMsgFromJni());
    }

    static {
        System.loadLibrary("hello-android-jni");
    }
    public native String getMsgFromJni();
}

Copy all folders that contain .so files in jni folder into jniLibs folder. Build and run.

Output

Output

Output

Intellij’s Trainings of the Month

This May we will have 3 events.

MOBILE IOS DEV USING SWIFT 2.0
16 – 17 May 2016
The workshop breaks down the processes of becoming an iOS developer.
Level: Beginner to Intermediate.
Sign up at: http://peatix.com/event/168172

=======

MOBILE ANDROID DEVELOPMENT
23 – 24 May 2016
The workshop breaks down the processes of becoming an Android developer.
Level: Beginner to Intermediate.
Sign up at: http://peatix.com/event/168176

=======
TEACH YOUR ROBOTS TO SEE, PERCEIVE SURROUNDINGS, AND COMPLETE TASKS.
28 – 29 May 2016.
OpenCV training using Python. Hands-on, practical exercises will be plenty.
9.00am to 6.00pm at Ovul Damansara.
Sign up at: http://peatix.com/event/167151

Grab your seats now!

Let’s change to world.

email: nurdin@intellij.my | call: 01126252058

</CODE>