Explore Enterprise Education Gitee Premium Gitee AI AI teammates
Fetch the repository succeeded.
Donate
Please sign in before you donate.
Scan WeChat QR to Pay
Cancel
Complete
Prompt
Switch to Alipay.
OK
Cancel
1 Star 0 Fork 12

小程序开发/AliRTCSample

forked from ding/AliRTCSample
Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
Already have an account? Sign in
文件
master
Branches (11)
master
web/3.0.0
dependabot/npm_and_yarn/Electron/http-cache-semantics-4.1.1
dependabot/npm_and_yarn/Electron/express-4.18.2
dependabot/npm_and_yarn/Electron/qs-6.5.3
dependabot/npm_and_yarn/Electron/decode-uri-component-0.2.2
dependabot/npm_and_yarn/Electron/loader-utils-and-html-webpack-plugin-1.4.2
dependabot/npm_and_yarn/Electron/minimatch-3.0.8
dependabot/npm_and_yarn/Electron/electron-18.3.7
dependabot/npm_and_yarn/Electron/terser-4.8.1
dependabot/npm_and_yarn/Electron/eventsource-1.1.1
master
Branches (11)
master
web/3.0.0
dependabot/npm_and_yarn/Electron/http-cache-semantics-4.1.1
dependabot/npm_and_yarn/Electron/express-4.18.2
dependabot/npm_and_yarn/Electron/qs-6.5.3
dependabot/npm_and_yarn/Electron/decode-uri-component-0.2.2
dependabot/npm_and_yarn/Electron/loader-utils-and-html-webpack-plugin-1.4.2
dependabot/npm_and_yarn/Electron/minimatch-3.0.8
dependabot/npm_and_yarn/Electron/electron-18.3.7
dependabot/npm_and_yarn/Electron/terser-4.8.1
dependabot/npm_and_yarn/Electron/eventsource-1.1.1
Clone or Download
Clone/Download
Prompt
To download the code, please copy the following command and execute it in the terminal
To ensure that your submitted code identity is correctly recognized by Gitee, please execute the following command.
When using the SSH protocol for the first time to clone or push code, follow the prompts below to complete the SSH configuration.
1 Generate RSA keys.
2 Obtain the content of the RSA public key and configure it in SSH Public Keys
To use SVN on Gitee, please visit the usage guide
When using the HTTPS protocol, the command line will prompt for account and password verification as follows. For security reasons, Gitee recommends configure and use personal access tokens instead of login passwords for cloning, pushing, and other operations.
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # Private Token
master
Branches (11)
master
web/3.0.0
dependabot/npm_and_yarn/Electron/http-cache-semantics-4.1.1
dependabot/npm_and_yarn/Electron/express-4.18.2
dependabot/npm_and_yarn/Electron/qs-6.5.3
dependabot/npm_and_yarn/Electron/decode-uri-component-0.2.2
dependabot/npm_and_yarn/Electron/loader-utils-and-html-webpack-plugin-1.4.2
dependabot/npm_and_yarn/Electron/minimatch-3.0.8
dependabot/npm_and_yarn/Electron/electron-18.3.7
dependabot/npm_and_yarn/Electron/terser-4.8.1
dependabot/npm_and_yarn/Electron/eventsource-1.1.1
AliRTCSample
/
Linux
/
Java
/
Samples
/
LinuxServerPushDemo.java
AliRTCSample
/
Linux
/
Java
/
Samples
/
LinuxServerPushDemo.java
LinuxServerPushDemo.java 16.69 KB
Copy Edit Raw Blame History
新野 authored 2024年10月28日 15:04 +08:00 . change rtc3.0 directory as default
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
package samples;
import com.ding.rtc.DingRtcEngine;
import com.ding.rtc.DingRtcEngineListener;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Random;
public class LinuxServerPushDemo {
static class RtcContext {
DingRtcEngine engine = null;
DingRtcEngineListener listener = null;
volatile boolean joinFinished = false;
int joinResult = -1;
volatile boolean quit = false;
// audio config
String pcmFilePath;
int pcmSampleRate = 16000;
int pcmChannels = 1;
int pcmReadFreq = 40;
volatile boolean isPushAudioStarted = false;
volatile boolean externalAudioFinished = false;
Thread externalAudioThread;
// video config
String videoYUVFilePath;
DingRtcEngine.DingRtcVideoFormat videoPixelFormat = DingRtcEngine.DingRtcVideoFormat.DingRtcVideoI420;
int videoWidth = 0;
int videoHeight = 0;
int videoRotation = 0;
int videoFps = 25;
volatile boolean isPushVideoStarted = false;
volatile boolean externalVideoFinished = false;
Thread externalVideoThread;
void reset() {
if (engine != null) {
engine.destroy();
}
engine = null;
listener = null;
if (externalAudioThread != null) {
try {
externalAudioThread.join();
} catch (InterruptedException e) {
log("[Demo] reset audio thread error:", e.toString());
}
}
if (externalVideoThread != null) {
try {
externalVideoThread.join();
} catch (InterruptedException e) {
log("[Demo] reset video thread error:", e.toString());
}
}
}
}
static class RtcListener extends DingRtcEngineListener {
private final RtcContext mRtcContext;
RtcListener(RtcContext context) {
mRtcContext = context;
}
@Override
public void onJoinChannelResult(int result, String channel, String userId, int elapsed) {
log("[Callback] onJoinChannelResult : " + result + ", channel : " + channel + ", uid : " + userId);
if (mRtcContext != null) {
mRtcContext.joinFinished = true;
mRtcContext.joinResult = result;
}
}
@Override
public void onLeaveChannelResult(int result) {
log("[Callback] onLeaveChannelResult : " + result);
}
}
private static void log(Object... args) {
if (args != null && args.length > 0) {
for (Object o : args) {
if (o != null) {
System.out.print(o);
}
}
System.out.println();
}
}
private static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
log("[Demo] main start");
LinuxServerPushDemo demo = new LinuxServerPushDemo();
demo.run(args);
log("[Demo] main finish");
}
public void run(String[] args) {
log("************** [Demo] begin ************** \n");
/**
* 配置音频、视频推流资源文件和相关参数
* 该示例音视频源为文件,其他形式资源流程基本一致
*/
RtcContext context = new RtcContext();
// 音频输入资源
context.pcmFilePath = "32000.pcm";
context.pcmSampleRate = 32000;
context.pcmChannels = 1;
// 一次读取40ms数据,控制io读取频率
context.pcmReadFreq = 25;
// 视频输入资源
context.videoYUVFilePath = "720_960.yuv";
context.videoPixelFormat = DingRtcEngine.DingRtcVideoFormat.DingRtcVideoI420;
context.videoWidth = 720;
context.videoHeight = 960;
context.videoRotation = 0;
context.videoFps = 25;
// 1. 初始化SDK
step_1_init_sdk(context);
// 2. 入会
step_2_join(context);
// 为了演示方便,同步等待join成功,等onJoinChannelResult回调触发
if (!wait_join_result(context)) {
// join fail
return;
}
// 3. 开始推音视频流
step_3_start_push_audio_video_data(context);
// 为了演示方便,同步等10s后,主动停止推流
sleep(10 * 1000);
// 设置结束flag,结束推流线程
context.quit = true;
// 4. 停止推音视频流
step_4_stop_push_audio_video_data(context);
// 5. 离会
step_5_leave(context);
// 6. 销毁
step_6_destroy(context);
context.reset();
}
private boolean wait_join_result(RtcContext context) {
while (!context.joinFinished) {
sleep(500);
}
if (context.joinResult != 0) {
// 入会失败,退出
// 需要检查authinfo是否请求正确
log("[Demo] join failed, return");
context.reset();
return false;
}
return true;
}
private void step_1_init_sdk(RtcContext context) {
initRtcEngine(context);
}
private void step_2_join(RtcContext context) {
DingRtcEngine.DingRtcAuthInfo authInfo = getAuthInfoFromServer(context);
if (context.engine != null) {
context.engine.joinChannel(authInfo, "张三");
}
}
private void step_3_start_push_audio_video_data(RtcContext context) {
startPushAudio(context);
startPushVideo(context);
}
private void step_4_stop_push_audio_video_data(RtcContext context) {
stopPushAudio(context);
stopPushVideo(context);
}
private void step_5_leave(RtcContext context) {
if (context.engine != null) {
context.engine.leaveChannel();
}
}
private void step_6_destroy(RtcContext context) {
if (context.engine != null) {
context.engine.destroy();
context.engine = null;
}
}
/**
* 停止推音频流数据
*/
private void stopPushAudio(RtcContext context) {
if (!context.isPushAudioStarted) {
return;
}
context.isPushAudioStarted = false;
if (context.engine != null) {
// 关闭推流
context.engine.publishLocalAudioStream(false);
// 关闭设置音频PCM推流
context.engine.setExternalAudioSource(false, context.pcmSampleRate, context.pcmChannels);
}
if (context.externalAudioThread != null) {
try {
context.externalAudioThread.join();
} catch (InterruptedException e) {
log("[Demo] doStopAudio thread error:", e.toString());
}
}
}
/**
* 开始推音频流数据
*/
private void startPushAudio(RtcContext context) {
if (context.isPushAudioStarted) {
return;
}
context.isPushAudioStarted = true;
if (context.engine != null) {
// 开启推流
context.engine.publishLocalAudioStream(true);
// 设置音频PCM推流
context.engine.setExternalAudioSource(true, context.pcmSampleRate, context.pcmChannels);
}
context.externalAudioThread = new Thread(() -> {
DingRtcEngine.DingRtcAudioFrame frame = new DingRtcEngine.DingRtcAudioFrame();
try (RandomAccessFile file = new RandomAccessFile(context.pcmFilePath, "r")) {
long sampleCount = 0;
// 16-bit pcm, 2byte
int bytesPerSample = 2;
int samplesToRead = context.pcmSampleRate / (1000 / context.pcmReadFreq);
int bufferSize = samplesToRead * context.pcmChannels * bytesPerSample;
byte[] buffer = new byte[bufferSize];
long delay = 0;
long startClock = System.currentTimeMillis();
long lastStatsClock = startClock;
while (!context.quit) {
long lastPos = file.getFilePointer();
int readBytes = file.read(buffer);
if (readBytes != bufferSize) {
// 读完文件,直接退出
// break;
// 如果想循环读
file.seek(0);
continue;
}
frame.bytesPerSample = bytesPerSample;
frame.samplesPerSec = context.pcmSampleRate;
frame.numChannels = context.pcmChannels;
frame.buffer = buffer;
frame.numSamples = readBytes / frame.bytesPerSample / frame.numChannels;
frame.timestamp = sampleCount * 1000 / context.pcmSampleRate;
delay = frame.timestamp;
long elapsed = System.currentTimeMillis() - startClock;
if (delay - elapsed > 5) {
sleep(delay - elapsed);
}
if (frame.numSamples > 0) {
int ret = context.engine.pushExternalAudioFrame(frame);
if (ret == 0) {
sampleCount += frame.numSamples;
} else {
file.seek(lastPos);
// sdk buffer full, wait some time ,ex: 40ms
if (ret == DingRtcEngine.DingRtcErrorCode.DingRtcErrorAudioBufferFull.getValue()) {
sleep(40);
}
}
}
long elpasedStats = System.currentTimeMillis() - lastStatsClock;
if (elpasedStats >= 2000) {
log("[Demo] audioPushThread pushExternalAudioFrame sampleCount:", sampleCount);
lastStatsClock = System.currentTimeMillis();
}
}
} catch (Exception e) {
log("[Demo] pushAudio error:", e.toString());
} finally {
context.externalAudioFinished = true;
}
}, "pub-audio");
context.externalAudioThread.start();
}
/**
* 停止推视频流数据
*/
private void stopPushVideo(RtcContext context) {
if (!context.isPushVideoStarted) {
return;
}
context.isPushVideoStarted = false;
if (context.engine != null) {
// 关闭推流
context.engine.publishLocalVideoStream(false);
context.engine.setExternalVideoSource(false, DingRtcEngine.DingRtcVideoTrack.DingRtcVideoTrackCamera);
}
if (context.externalVideoThread != null) {
try {
context.externalVideoThread.join();
} catch (InterruptedException e) {
log("[Demo] doStopAudio thread error:", e.toString());
}
}
}
/**
* 开始推视频流数据
*/
private void startPushVideo(RtcContext context) {
if (context.isPushVideoStarted) {
return;
}
context.isPushVideoStarted = true;
if (context.engine != null) {
// 开启推流
context.engine.publishLocalVideoStream(true);
// 设置音频PCM推流
context.engine.setExternalVideoSource(true, DingRtcEngine.DingRtcVideoTrack.DingRtcVideoTrackCamera);
}
context.externalVideoThread = new Thread(() -> {
try (RandomAccessFile file = new RandomAccessFile(context.videoYUVFilePath, "r")) {
long frameCount = 0;
DingRtcEngine.DingRtcVideoFormat pixelFormat = context.videoPixelFormat;
int bufferSize = calcBufferSize(pixelFormat, context.videoWidth, context.videoHeight);
long delay = 0;
long startClock = System.currentTimeMillis();
long lastStatsClock = startClock;
byte[] buffer = new byte[bufferSize];
DingRtcEngine.DingRtcVideoFrame frame = new DingRtcEngine.DingRtcVideoFrame();
while (!context.quit) {
long readStartClock = System.currentTimeMillis();
long lastPos = file.getFilePointer();
int readBytes = file.read(buffer);
if (readBytes != bufferSize) {
// 读完文件,直接退出
// break;
// 如果想循环读
file.seek(0);
continue;
}
frame.format = pixelFormat;
frame.width = context.videoWidth;
frame.height = context.videoHeight;
frame.lineSize[0] = context.videoWidth;
frame.lineSize[1] = context.videoWidth >> 1;
frame.lineSize[2] = context.videoWidth >> 1;
frame.rotation = context.videoRotation;
frame.videoFrameLength = bufferSize;
frame.buffer = buffer;
frame.timestamp = frameCount * 1000 / context.videoFps;
delay = frame.timestamp;
long elapsed = System.currentTimeMillis() - startClock;
if (delay - elapsed > 5) {
sleep(delay - elapsed);
}
int ret = context.engine.pushExternalVideoFrame(frame, DingRtcEngine.DingRtcVideoTrack.DingRtcVideoTrackCamera);
if (ret == 0) {
frameCount++;
} else {
file.seek(lastPos);
if (ret == DingRtcEngine.DingRtcErrorCode.DingRtcErrorVideoBufferFull.getValue()) {
// sdk buffer full, wait some time ,ex: 40ms
sleep(40);
}
}
long elpasedStats = System.currentTimeMillis() - lastStatsClock;
if (elpasedStats >= 5000) {
log("[Demo] videoPushThread pushExternalVideoFrame frameCount:", frameCount);
lastStatsClock = System.currentTimeMillis();
}
}
} catch (Exception e) {
log("[Demo] pushVideo error:", e.toString());
} finally {
context.externalVideoFinished = true;
}
}, "pub-video");
context.externalVideoThread.start();
}
/**
* 计算视频一帧数据大小
*/
int calcBufferSize(DingRtcEngine.DingRtcVideoFormat pixel_format, int width, int height) {
int buffer_size = 0;
switch (pixel_format) {
case DingRtcVideoI420:
case DingRtcVideoNV12:
case DingRtcVideoNV21: {
int half_width = (width + 1) >> 1;
int half_height = (height + 1) >> 1;
buffer_size = width * height + half_width * half_height * 2;
break;
}
case DingRtcVideoBGRA:
case DingRtcVideoARGB:
case DingRtcVideoRGBA:
case DingRtcVideoABGR:
buffer_size = width * height * 4;
break;
default:
break;
}
return buffer_size;
}
/**
* 初始化引擎
*/
private void initRtcEngine(RtcContext context) {
String dir = System.getProperty("user.dir");
// 设置日志路径
DingRtcEngine.setLogDirPath(dir);
// 初始化回调
RtcListener listener = new RtcListener(context);
// 初始化引擎
DingRtcEngine engine = DingRtcEngine.createInstance(listener, "");
context.engine = engine;
context.listener = listener;
}
/**
* TODO request from app server
* @return DingRtcAuthInfo
*/
private DingRtcEngine.DingRtcAuthInfo getAuthInfoFromServer(RtcContext context) {
DingRtcEngine.DingRtcAuthInfo authInfo = new DingRtcEngine.DingRtcAuthInfo();
authInfo.appId = "";
authInfo.channelId = "";
authInfo.userId = "";
authInfo.token = "";
// 注意 gslb字段推荐填空串
authInfo.gslb = "";
return authInfo;
}
}
Loading...
Report
Report success
We will send you the feedback within 2 working days through the letter!
Please fill in the reason for the report carefully. Provide as detailed a description as possible.
Please select a report type
Cancel
Send
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

Releases

No release

Contributors

All

Activities

can not load any more
Edit
About
Homepage
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/exphp/AliRTCSample.git
git@gitee.com:exphp/AliRTCSample.git
exphp
AliRTCSample
AliRTCSample
master
Going to Help Center

Search

Comment
Repository Report
Back to the top
Login prompt
This operation requires login to the code cloud account. Please log in before operating.
Go to login
No account. Register

AltStyle によって変換されたページ (->オリジナル) /