音频延时测算脚本

前言

	每次版本迭代需要测试音频的传输耗时,或者比较唇音不同步的时候也需要计算耗时。纯以人工计算显得很麻烦,因此写了该脚本根据日志信息计算传输耗时,并绘制散点图。
	主要思路就是通过读取终端配置信息,telnet连接上去,通过命令开启日志打印,对日志信息使用正则过滤,计算出传输的时间信息,计算差值。	

配置文件

[RemoteInfo]
host = 127.0.0.1
port = xxxx
username =  
password =   

音频延时测算

# encoding=utf-8
# 终端自动升级脚本
# --杨靖杰,2020/12/5
# 环境: python2

import re
import telnetlib
import time
import ConfigParser
import os
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

file_path = 'file_created_by_running\\'
def path_check(file_path):
    if not os.path.exists(file_path):
        os.makedirs(file_path)

def do_telnet(config, commands, filename):
    '''Telnet远程登录,并根据预置命令抓取打印保存'''

    filename1 = file_path + filename
    ff = open(filename1, 'w')
    # 连接Telnet服务器
    tn = telnetlib.Telnet(config[0], int(config[1]), timeout=10)
    # tn.set_debuglevel(2)
    # 输入登录用户名
    tn.read_until('Username:')
    # Windows程序 使用'\n\r'代表换行
    tn.write(config[2] + '\n\r')
    # 输入登录密码
    tn.read_until('Password:')
    tn.write(config[3] + '\n\r')

    # 登录完毕后执行命令
    for command in commands:
        tn.write(command + '\n\r')
    # 执行完毕后,终止Telnet连接(或输入exit退出)
    # tn.close()  # tn.write('exit\n')
    count = 0
    # 不应该实时读取解析
    # 写入文件进行分析
    while True:
        time.sleep(1)
        if count == 10:
            break

        count = count + 1
        # cmd编码格式gbk
        raw_file = tn.read_very_eager().decode('gbk').strip()
        ff.write(raw_file.encode('gbk'))
    ff.close()
    tn.write('xxxx' + '\n\r')
    tn.close()

def file_anyls(filename):
    '''根据传入的日志文件,过滤出hook1和hook4的timestamp以及对应的时间'''

    ff = open(file_path + filename, 'r')
    filename1 = filename + '_' + 'hook1'
    ff1 = open(file_path + filename1, 'w')
    filename2 = filename + '_' + 'hook4'
    ff2 = open(file_path + filename2, 'w')
    tt = ff.readlines()
    pat1 = re.compile(', ts[=].*?[,]')
    pat2 = re.compile('layer_ts[=].*?[ ]')
    pat3 = re.compile('capture_ts[=].*?[,]')
    pat4 = re.compile('now[=].*?[ ]')
    for lines in tt:
        if 'hook[1][RTP]' in lines:
            line1 = lines
            str1 = re.findall(pat1, line1)
            str2 = re.findall(pat2, line1)
            str3 = str1[0].strip(', ts=').strip(',') + ' ' + str2[0].strip('layer_ts=').strip(',') + '\n'
            ff1.write(str3)
        if 'hook[4][Frame]' in lines:
            line4 = lines.strip()
            str4 = re.findall(pat3, line4)
            str5 = re.findall(pat4, line4)
            str6 = str4[0].strip('capture_ts=').strip(',') + ' ' + str5[0].strip('now=').strip(',') + '\n'
            ff2.write(str6)
    ff.close()
    ff1.close()
    ff2.close()
    filenamelist = [filename, filename1, filename2]
    return filenamelist

def compare_join(filenamelist):
    '''实现类似linux join功能'''
    
    ff1 = open(file_path + filenamelist[1], 'r')
    ff2 = open(file_path + filenamelist[2], 'r')
    filename3 = 'compare_join'
    ff3 = open(file_path + filename3, 'w')
    tt1 = ff1.readlines()
    tt2 = ff2.readlines()
    for line2 in tt2:
        k2 = line2.strip('\n\r').split()
        for line1 in tt1:
            k1 = line1.strip('\n\r').split()
            if len(k2) != 0 and len(k1) != 0 and k1[0] == k2[0]:
                line3 = line1.strip('\n\r') + k2[1] + '\n'
                ff3.write(line3)
                break
    ff1.close()
    ff2.close()
    ff3.close()
    return filename3

def createList(filename):
    '''根据传入的过滤好的文件,计算第二列和第三列的差值,并返回一个list'''

    numlist = []
    count = 0
    ff = open(file_path + filename, 'r')
    tt = ff.readlines()
    ff.close()
    ff1 = open(file_path + 'numlist', 'w')
    for line in tt:
        count = count + 1
        if count == 1:
            continue
        en = line.strip().split(' ')
        if len(en) == 3:
            dd = int(en[2], 10) - int(en[1], 10)
            numlist.append(dd)
            ff1.write(str(dd) + '\n')

    ff1.close()
    return numlist

def numAlys(numlist):
    '''计算传入list的max, min, avg的值'''

    print "max:", max(numlist), "min:", min(numlist), "avg:", (sum(numlist)/len(numlist))

def generate_statistical_graph(numlist):
    '''绘制传入list的散点图'''

    y = numlist
    x = np.arange(1, len(numlist) + 1)

    plt.figure()
    plt.scatter(x,y,label='mnet_delay_1_4')
    plt.legend()
    plt.savefig(file_path + 'scatter.png')
    plt.show()


if __name__ == '__main__':
    # 配置选项
    cf = ConfigParser.ConfigParser()
    cf.read("Config.ini")
    Host = cf.get('RemoteInfo', 'host')  # Telnet服务器IP
    Port = cf.get('RemoteInfo', 'port')
    Username = cf.get('RemoteInfo', 'username')  # 登录用户名
    Password = cf.get('RemoteInfo', 'password')  # 登录密码
    config = [Host, Port, Username, Password]
    commands = ['commands']
    filename = 'mylog'
    path_check(file_path)
    do_telnet(config, commands, filename)
    filenamelist = file_anyls(filename)
    filename = compare_join(filenamelist)
    list1 = createList(filename)
    numAlys(list1)
    generate_statistical_graph(list1)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个使用Python语言试WebRTC音频延时的代码示例: ```python import sounddevice as sd import numpy as np import time # 设置采样率和录音时间 samplerate = 48000 duration = 5 # 单位为秒 # 录制原始音频 print("Recording original audio...") original_audio = sd.rec(int(samplerate * duration), samplerate=samplerate, channels=1, dtype='float32') sd.wait() # 播放原始音频 print("Playing original audio...") sd.play(original_audio, samplerate=samplerate) sd.wait() # 录制回放音频 print("Recording playback audio...") playback_audio = sd.rec(int(samplerate * duration), samplerate=samplerate, channels=1, dtype='float32') sd.wait() # 播放回放音频 print("Playing playback audio...") sd.play(playback_audio, samplerate=samplerate) sd.wait() # 计算音频延迟 delay = np.argmax(np.correlate(original_audio, playback_audio, mode='full')) / float(samplerate) print("Audio delay:", delay, "s") ``` 这个代码可以使用Python的`sounddevice`库来录制和播放音频,使用`numpy`库来计算音频延迟。具体步骤如下: 1. 设置采样率和录音时间,这里采用了48kHz的采样率和5秒的录音时间。 2. 录制原始音频,使用`sd.rec()`函数进行录音,返回的是一个`numpy`数组。 3. 播放原始音频,使用`sd.play()`函数进行音频回放。 4. 录制回放音频,同样使用`sd.rec()`函数进行录音。 5. 播放回放音频,同样使用`sd.play()`函数进行音频回放。 6. 计算音频延迟,使用`np.correlate()`函数计算原始音频和回放音频的互相关函数,然后使用`np.argmax()`函数找到互相关函数的峰值位置,最后除以采样率得出延迟时间。 需要注意的是,这个代码只是一个简单的示例,并没有考虑WebRTC的具体实现细节,例如AEC、AGC、NS等算法对音频延迟的影响。如果你需要更准确的延迟试结果,需要使用WebRTC提供的API或者第三方音频试工具。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值