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的更多相关文章

  1. Windows Phone 8初学者开发—第21部分:永久保存Wav音频文件

    原文 Windows Phone 8初学者开发—第21部分:永久保存Wav音频文件 第21部分:永久保存Wav音频文件 原文地址:http://channel9.msdn.com/Series/Win ...

  2. Unity录音

    上周做过Unity录音,(不知道的可以到网上查找一下,代码挺多的),不过只能录制麦克风的声音,项目需要同时录制背景音和麦克风传进去的声音,经过探索,现已可以录制: 首先需要知道,即使用电脑录音,想录制 ...

  3. 【一天一个小知识10/20】Unity安卓获取麦克风并录音保存。

    2021-10-20 10:42:16 #region 模块信息 // **************************************************************** ...

  4. unity自动保存项目

    原文来自于:http://wiki.unity3d.com/index.php?title=AutoSave#C.23_-_AutoSave.cs      (奋斗的菜鸟_1029633680) 很多 ...

  5. C#文本转语音并保存wav和MP3文件

    回顾上次写博客至今都有4个多月了,最近工作比较的忙没时间写博文.以后会多坚持写博文,与大家分享下最近遇到的问题.最近因为项目需要,研究了下用C#开发TTS.下面把大体的思路给大家说说,希望对大家有所帮 ...

  6. unity文件 PlayerPrefs.SetInt 保存 And PlayerPrefs.GetInt读取

    unity文件保存读取PlayerPrefs.SetInt   And  PlayerPrefs.GetInt using UnityEngine; using System.Collections; ...

  7. iOS开发系列--音频播放、录音、视频播放、拍照、视频录制

    --iOS多媒体 概览 随着移动互联网的发展,如今的手机早已不是打电话.发短信那么简单了,播放音乐.视频.录音.拍照等都是很常用的功能.在iOS中对于多媒体的支持是非常强大的,无论是音视频播放.录制, ...

  8. HTML5网页录音和压缩,边猜边做..(附源码)

    宣传一下自己的qq群: (暗号:C#交流) 欢迎喜欢C#,热爱C#,正在学习C#,准备学习C#的朋友来这里互相学习交流,共同进步 群刚建,人不多,但是都是真正热爱C#的 我也是热爱C#的 希望大家可以 ...

  9. iOS开发----音频播放、录音、视频播放、拍照、视频录制

    随着移动互联网的发展,如今的手机早已不是打电话.发短信那么简单了,播放音乐.视频.录音.拍照等都是很常用的功能.在iOS中对于多媒体的支持是非常强大的,无论是音视频播放.录制,还是对麦克风.摄像头的操 ...

  10. 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 ...

随机推荐

  1. php基础教程(一)

    语法: PHP的语法很简单 --直接看代码: <?php /*代码部分*/ ?> 这就是PHP代码的声明方式. 注:<? ?> 等这中写法也可以写,但是不建议这么写. 标记语句 ...

  2. Something Just Like This

    I've been reading books of old我遍读旧籍 The legends and the myths那些古老传奇和无边神秘 Achilles and his gold如阿喀琉斯和 ...

  3. 微信防红页面JS代码

    将Js代码复制粘贴到你网站所需要的页面,保存即可,完美实现防红,具体未测试,如果需要可以自己测试效果. <meta charset="utf-8″> <meta name= ...

  4. Linux基础第六章:逻辑卷的使用、扩容和磁盘配额

    一.逻辑卷的使用及扩容 1.概念优点及注意事项 2.使用命令及基本格式 3.创建逻辑卷 ①创建物理卷 ②创建卷组 ③创建逻辑卷 ④格式化.挂载yk26逻辑卷在/mnt下并在逻辑卷yk26下创建文件a. ...

  5. 【python】界面学习

    最近开始要用python做界面了,又是在百度的洪流中不断呛水.下面列举了很多我在过程中查询的内容以及我认为相对对我的认知有益的链接. 1.python有哪些做界面的工具 三个:python gui 中 ...

  6. 安卓10.0蓝牙HIDL的直通式初始化流程

    本文仅介绍扼要的流程,没有系统化介绍. 首先从system\bt\hci\src\hci_layer_android.cc文件的函数void hci_initialize() 开始初始化: void ...

  7. Tesstwo9.1.0配置步骤

    一,配置步骤 环境:Tesstwo9.1.0+Android10(华为)+Android11(模拟器) 1.查看tess-two的最新版本(GitHub - rmtheis/tess-two: For ...

  8. font-awesome vue/react 通用的图标

    在开发项目中遇到了矢量图标 一套绝佳的图标字体库和CSS框架 vue 中引入font-awesome 直接npm install font-awesome --save 就可以了,里边包含了样式和字体 ...

  9. bat脚本批量删除指定源码编译后的文件

    @echo off @REM 使循环内的set命令有效 setlocal enabledelayedexpansion set DIR_ROOT=%~dp0..\ for /f "delim ...

  10. Date 对象 定时器

    日期对象 Date 概述:date是表示日期时间的对象,主要的方法是获取时间和设置日期时间. date声明 使用new Date声明 有4种方式 1.不设参数 是获取当前的本地时间 var date ...