百度语音api调用

这周是第六周。

本周使用百度的api调用,利用线程池容纳线程进行语音的分析,这样不会因为语音太多而造成卡顿或者造成速度下降等问题。

package myThread;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import key.key;
import reco.voice_recog;

public class Main8 {
	//根目录
	public static String root_path="C:\\Users\\dell-pc\\Desktop\\new";
	//存储还没有被处理的路径
	public static List<String> existing_url;
	//存储路径
	public static List<String> url;//=new ArrayList<String>();
	//存储结果
	public static List<String> list;//=new ArrayList<String>();
	//lock the lists
	public static Lock lists_lock;// =  new ReentrantLock();
	//lock the path
	public static Lock path_lock;
	public static void main(String[] args)
	{
		existing_url=new ArrayList<String>();
		url=new ArrayList<String>();
		list=new ArrayList<String>();
		Main8 m=new Main8();
		//初始化线程
		Main8.myThread thread1=m.new myThread("1");
		Main8.myThread thread2=m.new myThread("2");
		Main8.myThread thread3=m.new myThread("3");
		//初始化锁
		lists_lock =  new ReentrantLock();
		path_lock =  new ReentrantLock();
		//线程池为4
		ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(4);
		exec.scheduleAtFixedRate(thread1, 1000, 1000, TimeUnit.MILLISECONDS);
		exec.scheduleAtFixedRate(thread2, 2000, 1000, TimeUnit.MILLISECONDS);
		exec.scheduleAtFixedRate(thread3, 3000, 1000, TimeUnit.MILLISECONDS);
		exec.scheduleAtFixedRate(m.new myThread2(), 8000, 3000, TimeUnit.MILLISECONDS);
	}
	public class myThread2 implements Runnable
	{
		public String str="print";
		@Override
		public void run() {
			// TODO Auto-generated method stub
			path_lock.lock();
			if(url.isEmpty())
				//打印list中的内容
				print_lists();
			path_lock.unlock();
		}
		public void print_lists()
		{
			if(list.isEmpty())
			{
				System.out.println("list is empty...");
				return ;
			}
			//System.out.println("this thread"+str+" empty()");
			for(int i=0;i<list.size();i++)
				System.out.println("this is thread "+str+list.get(i));
		}
		
	}
	public class myThread implements Runnable
	{
		public String str;
		
		public myThread(String str)
		{
			this.str=str;
			System.out.println(str);
		}
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			while(true) {
				
				path_lock.lock();
				if(is_Empty())
				{
				//path_lock.lock();
					System.out.println("this is thread "+str+" :updating the file");
					path_lock.unlock();
					//更新url内容
					if(existing_url.isEmpty())
					{
						update_urls(root_path);
						for(String k:url)
							System.out.println("this is thread "+str+" updating : "+k);
					}
					else
					{
						System.out.println("existing path is not empty!");
					}
				}
				else
				{
					path_lock.unlock();
					path_lock.lock();
					//取出音频文件
					String path=get();
					System.out.println("this is thread"+str+":I get the url"+path);
					path_lock.unlock();
					//分析音频文件,并存储在list中
					lists_lock.lock();
					try
					{
						add_list(get_json(path));
					}
					catch(Exception e)
					{
						e.printStackTrace();
					}
					lists_lock.unlock();
					
					//删除被分析过的音频文件
					delete_file(path);
					
				}

				
				//睡眠1000ms
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		//删除分析过的文件
		 public boolean delete_file(String fileName) {
			    //existing_url.remove(o)
			    for(int i=0;i<existing_url.size();i++)
			    	if(existing_url.get(i).equals(fileName))
			    		existing_url.remove(i);
		        File file = new File(fileName);
		        if (!file.exists()) {
		        	//返回错误
		            return false;
		        } else {
		            if (file.isFile())
		            	//成功删除
		                return file.delete();
		            else
		                return false;
		        }
		  }
		 
		 public void update_urls(String root_path)
		 {
			 File dirFile = new File(root_path);
			 if(dirFile.exists()&&dirFile.isDirectory())
			 {
				File[] file_lists=dirFile.listFiles();
				for(int i=0;i<file_lists.length;i++)
				{
					//将目录下的内容添加url
					System.out.println(file_lists[i].getPath());
					url.add(file_lists[i].getPath());
				}
			}
		 }
		public String get() {
			if(!url.isEmpty())
			{
				String str=url.get(0);
				url.remove(0);
				//将结果 存储在existing_url
				existing_url.add(str);
				//返回结果
				return str;
			}
			else
			{
				return "";
			}
		}
		public void  add_list(List<String> list2)
		{
			//将结果添加进list
			list.addAll(list2);
		}
		public boolean is_Empty() {
			//返回是否为空
			return url.isEmpty();
		}
		public List<String> get_json(String path)
		{
			//List<String> str= new voice_recog().get_string("‪C:\\Users\\dell-pc\\Desktop\\MyRecord .amr","amr", key.baidu_ID,key.baidu_key,key.baidu_secret);
			List<String> str=new voice_recog().get_string(path,"amr",
                    key.baidu_ID,key.baidu_key,key.baidu_secret);
			return str;
		}

	}
}

调用百度api,

设置请求参数和secret和secret_key,

接收返回的数据.

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.baidu.aip.speech.AipSpeech;
public class voice_recog {
	
	public List<String> get_string(String file,String type,
			String baidu_id,String baidu_key,String baidu_secret)
	{
		ArrayList<String> list=new ArrayList<String>();
		//Calendar calendar=Calendar.getInstance();
		//System.out.println(calendar.getTime().toString());
        AipSpeech client = new AipSpeech(baidu_id,baidu_key,baidu_secret);

        // 可选:设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 调用接口
        JSONObject res = client.asr(file, type, 8000, null);
        //System.out.println(res.toString(2));
        //calendar=Calendar.getInstance();
        //System.out.println(calendar.getTime().toString());
        JSONArray jsonarr= res.getJSONArray("result");
        for(int m=0;m<jsonarr.length();m++)
        {
        	list.add(jsonarr.getString(m));
        }
        return list;
	}
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值