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. js实现不同的域名 输出不同的结果

    js实现域名判断后跳转到指定网址,也适用于同一虚拟空间放多个网站: <script> try { if(self.location == "http://apple.baidu. ...

  2. 异步按照同步顺序执行的function

    function  step1 (callback) {     console.log(111111)     callback.call() } function  step2 (callback ...

  3. 进程间通信测试-signal

    截图 代码 #include <stdio.h> #include <unistd.h> #include <signal.h> #include <stri ...

  4. CentOS 7.9 环境下部署 MySQL 5.7 服务

    sudo setenforce Permissive sudo vi /etc/selinux/config SELINUX=permissive sudo systemctl stop firewa ...

  5. Vue.sync修饰符与this.$emit('update:xxx', newXXX)

    Vue通过prop进行双向数据绑定.子组件数据变化,一般只能通过 this.$emit(func, val) 回调父组件函数来传值给父组件. Vue2.3版本引入sync,作为一个事件绑定语法糖,当子 ...

  6. 1=C到底是哪个C

  7. PHP接口跨域问题的解决方案

    先来看一下问题 请求头有多余的参数 解决方案是配置允许 详细代码如下: // 可跨域域名列表$domains = [ 'http://localhost:8080', 'http://test.qqq ...

  8. 使用idea从零编写SpringCloud项目-Hystrix

    ps:Hystrix和Fegin里面使用的Hystrix,有些许区别.我理解的是Fegin.Hystrix主要是用于消费方在调用服务方接口时的异常处理,返回兜底数据等,而Hystrix则是消费方自己本 ...

  9. POJ3723 Conscription 题解

    start: 2021-08-04 16:56:50 题目链接: http://poj.org/problem?id=3723 题目内容: Description Windy has a countr ...

  10. 字节码 看 new String("abc")创建了几个对象

    感谢博主分享:https://www.cnblogs.com/zhaideyou/p/5875175.html 但是如果代码是这样子的: String str1 = "abc"; ...