【一天一个小知识10/20】Unity安卓获取麦克风并录音保存。
2021-10-20
10:42:16
#region 模块信息
// **********************************************************************
// Copyright (C) 2019 jiamiantech
// Please contact me if you have any questions
// File Name: Recording
// Author: romantic
// WeChat||QQ: at853394528 || 853394528
// **********************************************************************
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI; public class Recording : MonoBehaviour
{
public Text ShowTimeHint;//剩余时间的文字提示
public Button voiceBtn;
float tirecordingTimemer = 0;//录音时长限制
private string[] devices;
public AudioSource aud;
// Use this for initialization
void Start()
{
devices = Microphone.devices;
if (devices.Length != 0)
{
ShowTimeHint.text = "设备有麦克风:" + devices[0];
}
else
{
ShowTimeHint.text = "设备没有麦克风";
}
AddTriggersListener(voiceBtn.gameObject, EventTriggerType.PointerDown, (t) =>
{
Debug.Log("开始说话");
StartCoroutine("KeepTime");
//参数一:设备名字,null为默认设备;参数二:是否循环录制;参数三:录制时间(秒);参数四:音频率
aud.clip = Microphone.Start(devices[0], false, 15, 6000); });
AddTriggersListener(voiceBtn.gameObject, EventTriggerType.PointerUp, (t) =>
{
Debug.Log("结束说话");
StopCoroutine("KeepTime");
Microphone.End(devices[0]);
//直接播放
aud.Play();
string byteStr = AudioToByte(aud);
Debug.Log(byteStr);
//传输给服务器
//GameManager.GetInstance.tcpClient.SendMeToServer(ProtoType.T_S_Voice, byteStr);
});
}
//把录好的音段转化为base64的string。测试过不转base64直接用byte[]也是可以的
public string AudioToByte(AudioSource audio)
{
float[] floatData = new float[audio.clip.samples * audio.clip.channels];
audio.clip.GetData(floatData, 0);
byte[] outData = new byte[floatData.Length];
Buffer.BlockCopy(floatData, 0, outData, 0, outData.Length);
return Convert.ToBase64String(outData);
} //把base64的string转化为audioSource
public void ByteToAudio(AudioSource audioSource, string str)
{
byte[] bytes = Convert.FromBase64String(str);
float[] samples = new float[bytes.Length];
Buffer.BlockCopy(bytes, 0, samples, 0, bytes.Length);
audioSource.clip = AudioClip.Create("RecordClip", samples.Length, 1, 6000, false);
audioSource.clip.SetData(samples, 0);
audioSource.Play();
} IEnumerator KeepTime()
{
for (tirecordingTimemer = 15; tirecordingTimemer >= 0; tirecordingTimemer -= Time.deltaTime)
{
if (tirecordingTimemer <= 15)
{
ShowTimeHint.text = "你还可以录 " + (int)tirecordingTimemer + " 秒";
if (tirecordingTimemer < 1)
{
ShowTimeHint.text = "时间到";
Microphone.End(devices[0]);
}
}
yield return 0;
}
} //添加按钮监听类型
private void AddTriggersListener(GameObject obj, EventTriggerType eventID, UnityAction<BaseEventData> action)
{
EventTrigger trigger = obj.GetComponent<EventTrigger>();
if (trigger == null)
{
trigger = obj.AddComponent<EventTrigger>();
} if (trigger.triggers.Count == 0)
{
trigger.triggers = new List<EventTrigger.Entry>();
} UnityAction<BaseEventData> callback = new UnityAction<BaseEventData>(action);
EventTrigger.Entry entry = new EventTrigger.Entry();
entry.eventID = eventID;
entry.callback.AddListener(callback);
trigger.triggers.Add(entry);
}
}
【一天一个小知识10/20】Unity安卓获取麦克风并录音保存。的更多相关文章
- 【一天一个小知识10/20】Unity通过www获取json文本信息。
前提:领导要我在unity获取局域网服务器的文本信息.给了一个json的网络文本让我测试.我对于json以及服务器比较陌生.就直接去网上找相关的资料. 以下是自己测试的代码,没问题. 测试的网络jso ...
- HTML+CSS中的一些小知识
今天分享一些HTML.CSS的小知识,希望能够对大家有所帮助! 1.解决网页乱码的问题:最重要的是要保证各个环节的字符编码一致! (1)编辑器的编辑环境的字符集(默认字符集):Crtl+U 常见的编码 ...
- s性能优化方面的小知识
总结的js性能优化方面的小知识 前言 一直在学习javascript,也有看过<犀利开发Jquery内核详解与实践>,对这本书的评价只有两个字犀利,可能是对javascript理解的还不够 ...
- python小知识-__call__和类装饰器的结合使用,数据描述符__get__\__set__\__delete__(描述符类是Python中一种用于储存类属性值的对象)
class Decorator(): def __init__(self, f): print('run in init......') self.f = f def __call__(self, a ...
- DevExpress之GridControl控件小知识
DevExpress之GridControl控件小知识 一.当代码中的DataTable中有建数据关系时,DevExpress 的 GridControl 会自动增加一个子视图 .列名也就是子表的字段 ...
- 蓝牙Bluetooth技术小知识
蓝牙Bluetooth技术以及广泛的应用于各种设备,并将继续在物联网IoT领域担任重要角色.下面搜集整理了一些关于蓝牙技术的小知识,以备参考. 蓝牙Bluetooth技术始创于1994年,其名字来源于 ...
- javascript实用技巧,js小知识
一.js整数的操作 使用|0和~~可以将浮点转成整型且效率方面要比同类的parseInt,Math.round 要快,在处理像素及动画位移等效果的时候会很有用.性能比较见此. var foo = (1 ...
- (转自http://www.blogjava.net/moxie/archive/2006/10/20/76375.html)WebWork深入浅出
(转自http://www.blogjava.net/moxie/archive/2006/10/20/76375.html) WebWork深入浅出 本文发表于<开源大本营> 作者:钱安 ...
- 12个你未必知道的CSS小知识
虽然CSS并不是一种很复杂的技术,但就算你是一个使用CSS多年的高手,仍然会有很多CSS用法/属性/属性值你从来没使用过,甚至从来没听说过. 1.CSS的color属性并非只能用于文本显示 对于CSS ...
随机推荐
- 百度地图BMap实现在行政区域内做标注
使用环境 vue bmap.js element-ui 页面展示 前提步骤 在index中引入百度地图提供的js库 在使用的vue页面中实例化地图 <!-- 给id随便起给名字 --> & ...
- 基本的sql语法
1. SELECT: 用于从数据库中选取数据 SELECT name,value FROM table_name 2.SELECT DISTINCT 语句用于返回唯一不同的值(去重) 3.WHERE ...
- 【刷题-LeetCode】306. Additive Number
Additive Number Additive number is a string whose digits can form additive sequence. A valid additiv ...
- linux + opencv + cuvid中使用cv::cuda::GpuMat类的一些坑
1.我最终成功实现了opencv中利用cuvid实现GPU视频解码:核心代码是: 1 cv::cuda::GpuMat d_frame; 2 cv::Ptr<cv::cudacodec::Vid ...
- linux文件系统讲解(一)
首先拿个一个硬盘,不能直接使用,要进行分区,比如下面的一块内存: 如果要进行分区,那么怎么分区,所以要有一个内存,用来保存怎么分区的信息,该块内存的名字叫启动块(BootBlock),他的大小是固定的 ...
- golang中字符串、bytes类型切片、16进制字符串之间的转换
func main() { // 字符串转bytes类型 name := "马亚南" fmt.Println(name) // 马亚南 bName := []byte(name) ...
- StringBuilder类介绍
1 package cn.itcast.p2.stringbuffer.demo; 2 3 public class StringBuilderDemo { 4 public static void ...
- java-包与包之间的访问
1 package face_package; 2 3 import face_packagedemoA.DemoA; 4 5 /* 包(package) 6 * 1,对类文件进行分类管理. 7 * ...
- 虚拟化技术kvm,xen,vmware比较
目前市面上常用的虚拟机技术主要有KVM.xen.vmware. KVM是指基于Linux内核(Kernel-based)的虚拟机(Virtual Machine).KVM最大的好处就在于它是与Linu ...
- Hexo博客(Snail主题)搭建回顾概览
Hexo博客(Snail主题)搭建回顾概览 笔者搭建博客地址:https://saltyfishyjk.github.io 目录 Hexo博客(Snail主题)搭建回顾概览 Part 0 前言 写作背 ...