我是团结开发的初学者。我试图在团结中做一个Android应用程序,用户可以录制音频按下按钮,当他发布时,录制的音频必须在循环播放。 到目前为止,我学会了如何从麦克风录制音频,以及播放音频的播放功能。
我无法做的事情
1.Cannot使用按钮按住和释放功能 2.无法在项目目录中找到保存的录音。
我已按照this thread录制和播放音频 我已经实现了相同的代码块。 它现在正在做的是录制我的声音并在我按下按钮时录制它。
对此有任何帮助将不胜感激。
提前致谢。
这是我尝试过的代码实现:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class audiorecorder : MonoBehaviour
{
AudioClip reco;
// Use this for initialization
public void onClick() {
AudioSource aud;
aud = GetComponent<AudioSource>();
foreach(string device in Microphone.devices)
{
Debug.Log(device);
}
reco = Microphone.Start("Built-in Microphone", true, 10, 44100);
aud.clip = reco;
aud.Play();
}
}
答案 0 :(得分:1)
如果您想使用鼠标上下移动,则必须使用IPointDownHandler
命名空间中的IPointerUpHandler
和UnityEngine.EventSystems
接口。要使用系统默认麦克风,您应该为Microphone.Start
函数指定设备名称的空字符串
下面的脚本应该有效,但我没有机会测试它,因为我现在没有麦克风。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
//Use the PointerDown and PointerUP interfaces to detect a mouse down and up on a ui element
public class AudioRecorder : MonoBehaviour, IPointerDownHandler, IPointerUpHandler{
AudioClip recording;
//Keep this one as a global variable (outside the functions) too and use GetComponent during start to save resources
AudioSource audioSource;
private float startRecordingTime;
//Get the audiosource here to save resources
private void Start()
{
audioSource = GetComponent<AudioSource>();
}
public void OnPointerUp(PointerEventData eventData)
{
//End the recording when the mouse comes back up, then play it
Microphone.End("");
//Trim the audioclip by the length of the recording
AudioClip recordingNew = AudioClip.Create(recording.name, (int)((Time.time - startRecordingTime) * recording.frequency), recording.channels, recording.frequency, false);
float[] data = new float[(int)((Time.time - startRecordingTime) * recording.frequency)];
recording.GetData(data, 0);
recordingNew.SetData(data, 0);
this.recording = recordingNew;
//Play recording
audioSource.clip = recording;
audioSource.Play();
}
public void OnPointerDown(PointerEventData eventData)
{
//Get the max frequency of a microphone, if it's less than 44100 record at the max frequency, else record at 44100
int minFreq;
int maxFreq;
int freq = 44100;
Microphone.GetDeviceCaps("", out minFreq, out maxFreq);
if (maxFreq < 44100)
freq = maxFreq;
//Start the recording, the length of 300 gives it a cap of 5 minutes
recording = Microphone.Start("", false, 300, 44100);
startRecordingTime = Time.time;
}
}
答案 1 :(得分:0)
SavWav:(您需要将其作为脚本添加到您的项目中)code
using System.Threading;
(用于睡眠功能)
int frequency = 44100; //Wav format frequency
int numberOfSecondsToRecord = 10;
var rec = Microphone.Start("", false, numberOfSecondsToRecord, frequency);
Thread.Sleep(numberOfSecondsToRecord * 1000); //To miliseconds
if(rec != null)
{
SavWav.Save(Application.persistentDataPath + "/test.wav", rec);
}
上述代码的主要作用是启动麦克风,如果成功完成,则返回正在录制的现场音频的音频剪辑,您必须等到录制完成后才保存。