Unity录音保存wav
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.UI; public class Recording : MonoBehaviour { private int Frequency = 16000; //录音频率
private int MicSecond = 300; //保存300秒内的音频(超出则重新开始录制)
public Button bStart;
public Button bStop;
public Button bPlay;
public Text tTip;
public AudioSource au;
private string device; private string recordPath="";
void Awake() {
if (File.Exists("Config/recordPath"))
{
StreamReader file = new StreamReader("Config/recordPath", Encoding.UTF8);
recordPath = file.ReadLine().Trim();
file.Close();
}
}
void Start()
{
device = Microphone.devices[0];
bStart.onClick.AddListener(OnStartClick);
bStop.onClick.AddListener(OnStopClick);
bPlay.onClick.AddListener(OnPlayClick);
}
int recordLength = 0;
DateTime sTime;
void OnStartClick()
{
tTip.text += "\n开始录音....";
au.Stop();
au.loop = false;
au.mute = true;
au.clip = Microphone.Start(device, true, MicSecond, Frequency);
sTime = DateTime.Now;
} void OnStopClick()
{
tTip.text += "\n停止录音!"; if (!Microphone.IsRecording(device))
return;
Microphone.End(device);
au.Stop();
TimeSpan sub = new TimeSpan(DateTime.Now.Ticks-sTime.Ticks);
recordLength = sub.Seconds * Frequency;
WavFromClip("test.wav", au.clip); //将录音保存为wav
}
void OnStopClick(string relativePath)
{
tTip.text += "\n停止录音!"; if (!Microphone.IsRecording(device))
return;
Microphone.End(device);
au.Stop();
TimeSpan sub = new TimeSpan(DateTime.Now.Ticks-sTime.Ticks);
recordLength = sub.Seconds * Frequency;
WavFromClip(recordPath+relativePath+".wav", au.clip); //将录音保存为wav
} void OnPlayClick()
{
if (Microphone.IsRecording(device))
return;
if (au.clip == null)
return;
au.mute = false;
au.loop = false;
au.Play();
tTip.text += "\n播放录音....";
} public void WavFromClip(string WavPosition, AudioClip clip)
{
if (Microphone.IsRecording(null))
return;
Microphone.End(null); using (FileStream fs = CreateEmpty(WavPosition))
{
ConvertAndWrite(fs, au.clip);
WriteHeader(fs, au.clip); //wav文件头
}
} private FileStream CreateEmpty(string filepath)
{
FileStream fileStream = new FileStream(filepath, FileMode.Create);
byte emptyByte = new byte(); for (int i = 0; i < 44; i++) //为wav文件头留出空间
{
fileStream.WriteByte(emptyByte);
} return fileStream;
} private void ConvertAndWrite(FileStream fileStream, AudioClip clip)
{
//Debug.Log("————————"+recordLength);
float[] samples = new float[recordLength];
//float[] samples = new float[clip.samples];
clip.GetData(samples, 0); Int16[] intData = new Int16[samples.Length]; Byte[] bytesData = new Byte[samples.Length * 2]; int rescaleFactor = 32767; //to convert float to Int16 for (int i = 0; i < samples.Length; i++)
{
intData[i] = (short)(samples[i] * rescaleFactor);
Byte[] byteArr = new Byte[2];
byteArr = BitConverter.GetBytes(intData[i]);
byteArr.CopyTo(bytesData, i * 2);
}
fileStream.Write(bytesData, 0, bytesData.Length);
} private void WriteHeader(FileStream stream, AudioClip clip)
{
int hz = clip.frequency;
int channels = clip.channels;
int samples = clip.samples; stream.Seek(0, SeekOrigin.Begin); Byte[] riff = System.Text.Encoding.UTF8.GetBytes("RIFF");
stream.Write(riff, 0, 4); Byte[] chunkSize = BitConverter.GetBytes(stream.Length - 8);
stream.Write(chunkSize, 0, 4); Byte[] wave = System.Text.Encoding.UTF8.GetBytes("WAVE");
stream.Write(wave, 0, 4); Byte[] fmt = System.Text.Encoding.UTF8.GetBytes("fmt ");
stream.Write(fmt, 0, 4); Byte[] subChunk1 = BitConverter.GetBytes(16);
stream.Write(subChunk1, 0, 4); UInt16 two = 2;
UInt16 one = 1; Byte[] audioFormat = BitConverter.GetBytes(one);
stream.Write(audioFormat, 0, 2); Byte[] numChannels = BitConverter.GetBytes(channels);
stream.Write(numChannels, 0, 2); Byte[] sampleRate = BitConverter.GetBytes(hz);
stream.Write(sampleRate, 0, 4); Byte[] byteRate = BitConverter.GetBytes(hz * channels * 2); // sampleRate * bytesPerSample*number of channels, here 44100*2*2
stream.Write(byteRate, 0, 4); UInt16 blockAlign = (ushort)(channels * 2);
stream.Write(BitConverter.GetBytes(blockAlign), 0, 2); UInt16 bps = 16;
Byte[] bitsPerSample = BitConverter.GetBytes(bps);
stream.Write(bitsPerSample, 0, 2); Byte[] datastring = System.Text.Encoding.UTF8.GetBytes("data");
stream.Write(datastring, 0, 4); Byte[] subChunk2 = BitConverter.GetBytes(samples * channels * 2);
stream.Write(subChunk2, 0, 4); }
}
保存其他格式需要插入相关的动态链接库
Unity录音保存wav的更多相关文章
- Windows Phone 8初学者开发—第21部分:永久保存Wav音频文件
原文 Windows Phone 8初学者开发—第21部分:永久保存Wav音频文件 第21部分:永久保存Wav音频文件 原文地址:http://channel9.msdn.com/Series/Win ...
- Unity录音
上周做过Unity录音,(不知道的可以到网上查找一下,代码挺多的),不过只能录制麦克风的声音,项目需要同时录制背景音和麦克风传进去的声音,经过探索,现已可以录制: 首先需要知道,即使用电脑录音,想录制 ...
- 【一天一个小知识10/20】Unity安卓获取麦克风并录音保存。
2021-10-20 10:42:16 #region 模块信息 // **************************************************************** ...
- unity自动保存项目
原文来自于:http://wiki.unity3d.com/index.php?title=AutoSave#C.23_-_AutoSave.cs (奋斗的菜鸟_1029633680) 很多 ...
- C#文本转语音并保存wav和MP3文件
回顾上次写博客至今都有4个多月了,最近工作比较的忙没时间写博文.以后会多坚持写博文,与大家分享下最近遇到的问题.最近因为项目需要,研究了下用C#开发TTS.下面把大体的思路给大家说说,希望对大家有所帮 ...
- unity文件 PlayerPrefs.SetInt 保存 And PlayerPrefs.GetInt读取
unity文件保存读取PlayerPrefs.SetInt And PlayerPrefs.GetInt using UnityEngine; using System.Collections; ...
- iOS开发系列--音频播放、录音、视频播放、拍照、视频录制
--iOS多媒体 概览 随着移动互联网的发展,如今的手机早已不是打电话.发短信那么简单了,播放音乐.视频.录音.拍照等都是很常用的功能.在iOS中对于多媒体的支持是非常强大的,无论是音视频播放.录制, ...
- HTML5网页录音和压缩,边猜边做..(附源码)
宣传一下自己的qq群: (暗号:C#交流) 欢迎喜欢C#,热爱C#,正在学习C#,准备学习C#的朋友来这里互相学习交流,共同进步 群刚建,人不多,但是都是真正热爱C#的 我也是热爱C#的 希望大家可以 ...
- iOS开发----音频播放、录音、视频播放、拍照、视频录制
随着移动互联网的发展,如今的手机早已不是打电话.发短信那么简单了,播放音乐.视频.录音.拍照等都是很常用的功能.在iOS中对于多媒体的支持是非常强大的,无论是音视频播放.录制,还是对麦克风.摄像头的操 ...
- PC-1500的代码存入WAV文件
目录 第1章保存 1 1.1 操作 1 1.2 波形说明 4 1.3 波形整形 5 1.4 压缩 8 第2章载入 9 2.1 操作 9 2.2 音量 9 ...
随机推荐
- vue编辑修改,点击取消操作时,table内的内容不变
1.父组件内 2.子组件内(使用JSON.parse(JSON.stringify(xxx值))) 进行深拷贝
- Swift中 堆(heap)和栈(stack)的区别
1.内存空间分为堆空间和栈空间 2.堆->引用类型(对象.函数.闭包) 栈->值类型(结构体.枚举.元组) 3.值类型赋值->深拷贝 引用类型赋值->浅拷贝 let a = ...
- 加载Assetbundle
using UnityEngine;using System.Collections;using UnityEngine.SceneManagement; /// <summary>/// ...
- IE浏览器a标签无法下载问题解决(IE浏览器a标签download属性不兼容问题解决)
//下载文件流函数,只支持get方法. export function downBlob(payload) { return new Promise(((resolve, reject) => ...
- pandas学习之 - excel篇
一.读取Excel文件 read_excel() # 读取excel文件(需要安装xlrd和openpyxl两个模块) 1.方法使用了Python的 xlrd 模块来读取Excel2003(.xls ...
- Knowledge Fusion例子
#! NX/KF 5.0 # #************************************************************************************ ...
- ssh反向通信
##先决条件为:一个有公网IP的VPS(虚拟主机),我使用的是国内的腾讯云,您也可以选择阿里云,亚马逊等各种厂商产品.这台机器的操作系统为 centos 7.0 ,IP 为 A.A.A.A #双内网主 ...
- MVC内置对象
MVC内置函数 ----HTML页 <!DOCTYPE html> <html> <head> <meta charset="utf-8&q ...
- 前端使用JSEncrypt进行加密和解密
下载链接:https://www.bootcdn.cn/jsencrypt/ 使用方法: 1.引入jsencrypt 2.使用方法 // 加密公钥 const key = `xxxxxx`; func ...
- SaltStack学习笔记
SaltStack三大功能: 1. 远程执行 2. 配置管理 (状态) 3.云管理 运维三板斧:监控.执行.配置 四种运行方式: 1.Local 2. Minion/Master C/S架构 3 ...