######################################################
## 此脚本对声音文件首尾无声段进行裁剪。具体功能是： ##
## 对声音文件进行端点检测，去掉前端和后端的无声段， ##
## 仅保存中间的有效段落。                           ##
## Written by Qibin Ran(ranqibin@126.com).          ##
## 2019-02-06                                       ##
######################################################

form 对原始声音文件进行端点检测并将经过端点检测的声音文件存入新的文件夹
	comment 原始声音文件所在的文件夹地址
	text input_Directory C:\Users\dell\Desktop\2020年5月19日——端点检测与声音提取、自动标注起终点\1声音截取
	comment 设置声音文件前部端点检测分贝值：
	positive dBlevel1 40
	comment 设置声音文件后部端点检测分贝值：
	positive dBlevel2 40
	comment	经过端点检测的声音文件的保存地址
	text output_Directory	C:\Users\dell\Desktop\2020年5月19日——端点检测与声音提取、自动标注起终点\1声音截取\0Cut
endform

if left$(input_Directory$,1)<>"\"
	input_Directory$=input_Directory$+"\"
endif

if left$(output_Directory$,1)<>"\"
	output_Directory$=output_Directory$+"\"
endif

createDirectory: output_Directory$

Create Strings as file list... fileList 'input_Directory$'*.wav
	numberOfFiles = Get number of strings

for ifile from 1 to numberOfFiles
	select Strings fileList
	fileName$ = Get string... 'ifile'

	Read from file... 'input_Directory$''fileName$'
	current_sound$ = selected$("Sound")

	select Sound 'current_sound$'
	To TextGrid... wordseg wordseg
	select Sound 'current_sound$'

	start=Get starting time
	finish=Get finishing time

	select Sound 'current_sound$'
	plus TextGrid 'current_sound$'
	Edit
	
	editor TextGrid 'current_sound$'
	
		Select... 0 0
		Show analyses... "yes" "no" "yes" "no" "no" 10
		Intensity settings... -50.0 100.0 "mean energy" "yes"

for i from 1 to finish*10
    i=i-1+0.01
    Move cursor to... i
    int=Get intensity
	if int <> undefined and int >= dBlevel1
		Add interval on tier 1
		i=9999
	endif
endfor

for i from 1 to finish*100
    x=finish-(i*0.01)
    Move cursor to... x
    int=Get intensity
	if int <> undefined and int >= dBlevel2
		Add interval on tier 1
		i=9999
	endif
endfor
endeditor

	select TextGrid 'current_sound$'
	select Sound 'current_sound$'
	Edit

	for i from 1 to 2

		select TextGrid 'current_sound$'
		start = Get time of point... 1 1
		finish = Get time of point... 1 2

		editor Sound 'current_sound$'
			Select... 'start' 'finish'
                	Extract selection
        	endeditor

        	select Sound untitled
        	Write to WAV file... 'output_Directory$''current_sound$'.wav

        	select Sound untitled
        	Remove
	endfor
	select all
	minus Strings fileList
	Remove
endfor

select all
Remove

exit OK！所有声音文件已经处理！