陈寒丫丫 2022-11-20 15:51 采纳率: 45.5%
浏览 0
已结题

android 百度识别功能

我有一个需求,我想在我的音乐播放器想加入一个百度语音识别功能。在搜索页加了一个按钮,跳转到百度识别界面,返回识别结果,调用搜索歌曲功能。

自建SpeechRecognitionActivity.java

public class SpeechRecognitionActivity extends AppCompatActivity implements EventListener {
    protected SearchEditText etSearch;
    protected Button startBtn;  //
    protected Button stopBtn; //
    private EventManager asr;//语音识别核心库

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

        ImageView asr_gif = (ImageView) findViewById(R.id.img_gif);
        Glide.with(this).load(R.drawable.asr).into(asr_gif);

        initPermission();
        initView();

        // 初始化EventEventManager对象
        asr = EventManagerFactory.create(this, "asr");
        // 注册自己的输出事件类
        asr.registerListener(this);
    }

    /**
     * android 6.0 以上需要动态申请权限
     */
    private void initPermission() {
        String permissions[] = {Manifest.permission.RECORD_AUDIO,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.INTERNET,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };

        ArrayList<String> toApplyList = new ArrayList<String>();

        for (String perm : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {
                toApplyList.add(perm);
            }
        }
        String tmpList[] = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()) {
            ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList), 123);
        }

    }

    /**
     * 权限申请回调,可以作进一步处理
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // 此处为android 6.0以上动态授权的回调,用户自行实现。
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 初始化控件
     */
    private void initView() {
        etSearch = (SearchEditText) findViewById(R.id.et_search);
        startBtn = (Button) findViewById(R.id.btn_start);
        stopBtn = (Button) findViewById(R.id.btn_stop);

        startBtn.setOnClickListener(new View.OnClickListener() {//开始
            @Override
            public void onClick(View v) {
                asr.send(SpeechConstant.ASR_START, "{}", null, 0, 0);
            }
        });
        stopBtn.setOnClickListener(new View.OnClickListener() {//停止
            @Override
            public void onClick(View v) {
                asr.send(SpeechConstant.ASR_STOP, "{}", null, 0, 0);
            }
        });
    }

    /**
     * 自定义输出事件类 EventListener 回调方法
     */
    @Override
    public void onEvent(String name, String params, byte[] data, int offset, int length) {
        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_PARTIAL)) {
            // 识别相关的结果都在这里
            if (params == null || params.isEmpty()) {
                return;
            }
            if (params.contains("\"final_result\"")) {
                // 一句话的最终识别结果
                Log.i("asr.event", params);

                Gson gson = new Gson();
                AsrResponseBean asRresponse = gson.fromJson(params, AsrResponseBean.class);//数据解析转实体bean

                if(asRresponse == null) return;
                //从日志中,得出Best_result的值才是需要的,但是后面跟了一个中文输入法下的逗号,
                if(asRresponse.getBest_result().contains(",")){//包含逗号  则将逗号替换为空格
                    etSearch.setText(asRresponse.getBest_result().replace(',',' ').trim());//替换为空格之后,通过trim去掉字符串的首尾空格


                }else {//不包含
                    etSearch.setText(asRresponse.getBest_result().trim());

                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //发送取消事件
        asr.send(SpeechConstant.ASR_CANCEL, "{}", null, 0, 0);
        //退出事件管理器
        // 必须与registerListener成对出现,否则可能造成内存泄露
        asr.unregisterListener(this);
    }
}

SearchActivity.java

public class SearchActivity extends BaseActivity<SearchPresenter> implements SearchContract.View {
    private static final String TAG = "SearchActivity";

    public static final String KEYWORDS = "keywords";

    @BindView(R.id.tl_searchhistory)
    SearchHistoryTagLayout tlHistory;
    @BindView(R.id.rv_hotsearch)
    RecyclerView rvHotSearch;
    @BindView(R.id.et_search)  // 搜索框
    SearchEditText etSearch;
    @BindView((R.id.iv_speech))  // 语音识别
    ImageView iv_speech;

    private HotSearchAdapter adapter;
    private List<SearchHistoryBean> stringList = new ArrayList<>();
    private HotSearchDetailBean searchDetailBean;
    private RikkaMusicDialog isDeleteDialog;

    @Override
    protected void onCreateView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_search);

        ImmersionBar.with(this)
                .transparentBar()
                .statusBarColor(R.color.colorPrimary)
                .statusBarDarkFont(false)
                .init();

    }

    @Override
    protected SearchPresenter onCreatePresenter() {
        return new SearchPresenter(this);
    }

    @Override
    protected void initModule() {
        ButterKnife.bind(this);
    }

    @Override
    protected void initData() {
        setBackBtn(getString(R.string.colorWhite));
        setEditText(getString(R.string.colorTransWithe));
        setRightSearchButton();

        adapter = new HotSearchAdapter(this);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        rvHotSearch.setLayoutManager(manager);
        rvHotSearch.setAdapter(adapter);
        adapter.setListener(searchListener);
        showDialog();
        mPresenter.getHotSearchDetail();
    }

    @Override
    protected void onResume() {
        super.onResume();
        stringList.clear();

        //从GreenDao里拿搜索历史
        if (SearchHistoryDaoOp.queryAll(this) != null) {
            stringList = SearchHistoryDaoOp.queryAll(this);
        }
        tlHistory.addHistoryText(stringList, tagListener);
    }

    private SearchHistoryTagLayout.OnHistoryTagClickListener tagListener = position -> {
        String keywords = stringList.get(position).getKeyowrds();
        searchSong(keywords);
    };

    private HotSearchAdapter.OnHotSearchAdapterClickListener searchListener = position -> {
        if (searchDetailBean != null) {
            String keywords = searchDetailBean.getData().get(position).getSearchWord();
            searchSong(keywords);
        }
    };


    @Override
    @OnClick({R.id.iv_search_name, R.id.iv_rubbish_bin, R.id.iv_speech})
    public void onClick(View v) {
        if (ClickUtil.isFastClick(1000, v)) {
            return;
        }
        Intent intent = new Intent();
        switch (v.getId()) {
            // TODO
            case R.id.iv_search_name:
                String keywords = etSearch.getKeyWords();
                if (!TextUtils.isEmpty(keywords)) {
                    searchSong(keywords);
                } else {
                    ToastUtils.show("请输入关键字!");
                }
                break;
            case R.id.iv_speech:
                intent.setClass(SearchActivity.this, SpeechRecognitionActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_rubbish_bin:
                showIsDeleteAllDialog();
                break;
        }
    }

    private void showIsDeleteAllDialog() {
        if (isDeleteDialog == null) {
            isDeleteDialog = new RikkaMusicDialog.Builder(this)
                    .setMsg(R.string.should_delete_all_search_history)
                    .setNegativeText(R.string.dialog_cancel)
                    .setPositiveText(R.string.dialog_search_history_clear)
                    .setNegativeClickListener((dialog, which) -> {
                        dialog.dismiss();
                    })
                    .setPositiveClickListener((dialog, which) -> {
                        dialog.dismiss();
                        SearchHistoryDaoOp.deleteAllData(this);
                        stringList = SearchHistoryDaoOp.queryAll(this);
                        tlHistory.addHistoryText(stringList, tagListener);
                    }).create();
        }
        if (!isDeleteDialog.isShowing()) {
            isDeleteDialog.show();
        }
    }

    //根据关键字去搜索
    private void searchSong(String keywords) {
        stringList.add(new SearchHistoryBean(keywords));
        if (stringList.size() > 10) {
            stringList.remove(0);
        }
        for (int i = 0; i < stringList.size() - 1; i++) {
            //去重
            if (stringList.get(i).getKeyowrds().equals(keywords)) {
                stringList.remove(i);
                break;
            }
        }
        SearchHistoryDaoOp.saveData(this, stringList);

        Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
        intent.putExtra(KEYWORDS, keywords);
        startActivity(intent);
    }

    @Override
    public void onGetHotSearchDetailSuccess(HotSearchDetailBean bean) {
        hideDialog();
        LogUtil.d(TAG, "onGetHotSearchDetailSuccess : " + bean);
        searchDetailBean = bean;
        List<HotSearchDetailBean> adapterList = new ArrayList<>();
        adapterList.add(searchDetailBean);
        adapter.notifyDataSetChanged(adapterList);
    }

    @Override
    public void onGetHotSearchDetailFail(String e) {
        hideDialog();
        LogUtil.e(TAG, "onGetHotSearchDetailFail : " + e);
        ToastUtils.show(e);
    }

    @Override
    public void onGetSongSearchSuccess(SongSearchBean bean) {

    }

    @Override
    public void onGetSongSearchFail(String e) {

    }

    @Override
    public void onGetFeedSearchSuccess(FeedSearchBean bean) {

    }

    @Override
    public void onGetFeedSearchFail(String e) {

    }

    @Override
    public void onGetSingerSearchSuccess(SingerSearchBean bean) {

    }

    @Override
    public void onGetSingerSearchFail(String e) {

    }

    @Override
    public void onGetAlbumSearchSuccess(AlbumSearchBean bean) {

    }

    @Override
    public void onGetAlbumSearchFail(String e) {

    }

    @Override
    public void onGetPlayListSearchSuccess(PlayListSearchBean bean) {

    }

    @Override
    public void onGetPlayListSearchFail(String e) {

    }

    @Override
    public void onGetRadioSearchSuccess(RadioSearchBean bean) {

    }

    @Override
    public void onGetRadioSearchFail(String e) {

    }

    @Override
    public void onGetUserSearchSuccess(UserSearchBean bean) {

    }

    @Override
    public void onGetUserSearchFail(String e) {

    }

    @Override
    public void onGetSynthesisSearchSuccess(SynthesisSearchBean bean) {

    }

    @Override
    public void onGetSynthesisSearchFail(String e) {

    }
}

界面展示:
搜索页,目前做的效果,点击右上角的语音ImageVie跳转到百度语音页面

img

百度语音识别页面

img

  • 写回答

0条回答 默认 最新

    报告相同问题?

    问题事件

    • 已结题 (查看结题原因) 11月25日
    • 创建了问题 11月20日

    悬赏问题

    • ¥15 距离软磁铁一定距离的磁感应强度大小怎么求
    • ¥15 霍尔传感器hmc5883l的xyz轴输出和该点的磁感应强度大小的关系是什么
    • ¥15 vscode开发micropython,import模块出现异常
    • ¥20 Excel数据自动录入表单并提交
    • ¥30 silcavo仿真,30分钟,只需要代码
    • ¥15 FastReport 怎么实现打印后马上关闭打印预览窗口
    • ¥15 利用3支股票数据估计其均值和方差的95%置信区间。
    • ¥15 微信小程序运行一项功能时,弹出未知错误弹框,检查代码没有问题
    • ¥15 ATAC测序生成self-pseudo replicates之前是否要进行去线粒体reads
    • ¥15 python模糊字匹配函数问题