I am using System.Media.SoundPlayer to play some wav files in my project.
Is it possible to change the volume of this SoundPlayer? If there is no way to do that, how can I change the volume of my computer using C#?
From SoundPlayer adjustable volume:
Unfortunately SoundPlayer doesn't provide an API for changing the volume. You could use the MediaPlayer class:
using System.Windows.Media;
public class Sound
{
private MediaPlayer m_mediaPlayer;
public void Play(string filename)
{
m_mediaPlayer = new MediaPlayer();
m_mediaPlayer.Open(new Uri(filename));
m_mediaPlayer.Play();
}
// `volume` is assumed to be between 0 and 100.
public void SetVolume(int volume)
{
// MediaPlayer volume is a float value between 0 and 1.
m_mediaPlayer.Volume = volume / 100.0f;
}
}
You'll also need to add references to the PresentationCore and WindowsBase assemblies.
Related
Let me start by saying that this is my first time opening up a question here. If I'm unclear in my code formatting or have expressed myself poorly, please let me know and I'd be happy to adjust.
I'm doing conceptual design for a tool to be used in Unity (C#) to allow us to "stream" the output of an AudioSource, in real-time, and then have that same audio be played back from a different GameObject. In essence, we would have a parallel signal being stored in a buffer while the original AudioSource functions as one would expect, sending it's playing clip into the mixer just as is normal.
To achieve this I'm trying to use the audio thread and the OnAudioFilterRead() function. To extract the floating point audio data to pipe into OnAudioFilterRead() i'm using AudioSource.GetOutputData, storing that into an array and then supplying the array to the audio filter. I'm also creating an empty AudioClip, setting it's data from the same array and playing that AudioClip on the new GameObject.
Right now I have the audio being played from the new GameObject, but the result is very distorted and unpleasant, which i'm chalking up to one or more of the following;
The audio buffer is being written to/read from in an unsynched manner
Unitys samplerate is causing problems with the clip. Have tried both 44.1khz and 48khz with subpar results, as well as playing around with import settings on clips. Documentation for Unity 2018.2 is very weak and a lot of older methods are now deprecated.
Aliens.
Ideally, I would be able to stream back the audio without audible artefacts. Some latency i can live with (~30-50ms) but not poor audio quality.
Below is the code that is being used. This script is attached to the GameObject that is to receive this audio signal from the original emitter, and it has its own AudioSource for playback and positioning.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
public class ECO_receiver : MonoBehaviour {
public AudioSource emitterSend;
private AudioSource audioSource;
public AudioClip streamedClip;
public bool debugSampleData;
private float[] sampleDataArray;
public float sampleSize;
public float sampleFreq;
private int outputSampleRate;
public bool _bufferReady;
void Start () {
audioSource = GetComponent<AudioSource>();
sampleSize = emitterSend.clip.samples;
sampleFreq = emitterSend.clip.frequency;
sampleDataArray = new float[2048];
streamedClip = AudioClip.Create("audiostream", (int)sampleSize, 1, (int)sampleFreq, false);
audioSource.clip = streamedClip;
audioSource.Play();
_bufferReady = true;
}
private void FixedUpdate()
{
if (emitterSend.isPlaying && _bufferReady == true)
{
FillAudioBuffer();
}
else if (!emitterSend.isPlaying)
{
Debug.Log("Emitter is not playing!");
}
if (debugSampleData && sampleDataArray != null && Input.GetKeyDown("p"))
{
for (int i = 0; i < sampleDataArray.Length; i++)
{
Debug.Log(sampleDataArray[i]);
}
}
else if (sampleDataArray == null)
{
Debug.Log("No data in array!");
}
}
void FillAudioBuffer()
{
emitterSend.GetOutputData(sampleDataArray, 0);
streamedClip.SetData(sampleDataArray, 0);
_bufferReady = false;
}
void OnAudioFilterRead(float[] data, int channels)
{
if (!_bufferReady)
{
for (int i = 0; i < data.Length; i++)
{
data[i] = (float)sampleDataArray[i];
}
_bufferReady = true;
}
}
}
Greatly appreciate any wisdom I might be granted! Thank you!
I have a class Sounds.cs that manages playing sounds in my form, and I want to be able to adjust the volume to decimal value. Is there a way to change the volume of a sound being played with a SoundPlayer object? Or is there perhaps a different way to play sound that makes this possible?
Unfortunately SoundPlayer doesn't provide an API for changing the volume. You could use the MediaPlayer class:
using System.Windows.Media;
public class Sound
{
private MediaPlayer m_mediaPlayer;
public void Play(string filename)
{
m_mediaPlayer = new MediaPlayer();
m_mediaPlayer.Open(new Uri(filename));
m_mediaPlayer.Play();
}
// `volume` is assumed to be between 0 and 100.
public void SetVolume(int volume)
{
// MediaPlayer volume is a float value between 0 and 1.
m_mediaPlayer.Volume = volume / 100.0f;
}
}
You'll also need to add references to the PresentationCore and WindowsBase assemblies.
The name 'Microphone' does not exist in the current context. getting this error when opening an unity(version 5.6.0f3) project is visual studio 2017 in window 8.
[RequireComponent (typeof (AudioSource))]
public class SingleMicrophoneCapture : MonoBehaviour
{
//A boolean that flags whether there's a connected microphone
private bool micConnected = false;
//The maximum and minimum available recording frequencies
private int minFreq;
private int maxFreq;
//A handle to the attached AudioSource
public AudioSource goAudioSource;
public AudioClip recordedAudioClip;
[HideInInspector]
public AudioClip myAudioClip;
//public Text fileExist;
bool startRecording = false;
public Sprite[] recordingSprites;
public int count =0;
//int recordedFileCount =0;
public bool isDefaultAudioPlaying = false;
[SerializeField]
public Sprite[] playSprites;
public GameObject forwardButton;
public GameObject backwardButton;
public GameObject playButton;
public GameObject replayButton;
//Use this for initialization
public AudioClip[] allAudioClips;
public string storyName;
float[] samples;
public Dictionary<int,float> recordedClipDict;
void Start()
{
//ReplayButtonClicked ();
//Check if there is at least one microphone connected
recordedAudioClip= null;
if(Microphone.devices.Length <= 0)
{
//Throw a warning message at the console if there isn't
Debug.LogWarning("Microphone not connected!");
}
else //At least one microphone is present
{
//Set 'micConnected' to true
micConnected = true;
//Get the default microphone recording capabilities
Microphone.GetDeviceCaps(null, out minFreq, out maxFreq);
//According to the documentation, if minFreq and maxFreq are zero, the microphone supports any frequency...
if(minFreq == 0 && maxFreq == 0)
{
//...meaning 44100 Hz can be used as the recording sampling rate
maxFreq = 44100;
}
//Get the attached AudioSource component
goAudioSource = this.GetComponent<AudioSource>();
// mainAudioSource = Camera.main.GetComponent<AudioSource> ();
}
}
how to solve this.
You are getting this error because you using a platform that do not support the Microphone API. One of the platforms that do not support the Microphone API is the WebGL. There might be other platforms other than WebGL without Microphone support.
Switch to a platform that supports the Microphone API from the Build Settings.
You can also use Unity's preprocessor directives to guard it and make sure that the Microphone API is not used when using platforms that do not support it or did not implement it.
#if !UNITY_WEBGL
//YOUR Microphone CODE HERE
#endif
If you really need Microphone in WebGL with Unity, make a plugin or use this one(Not free).
We can not see your using statements.
But it seems like your are missing
using UnityEngine.AudioModule;
I'm making a program in Visual Studio 2015 (C#) and I want to add sound effects to it. However, I have looked up countless tutorials but none of them seem to work, and gave me tons of errors. If anyone can give me a code to play a .wav file from resource files then I would be very grateful
How to: Play Sounds in an Application
Add the following method code under the button1_Click event hander :
System.Media.SoundPlayer player =
new System.Media.SoundPlayer();
player.SoundLocation = #"C:\Users\Public\Music\Sample Music\xxxx.wav";
player.Load();
player.Play();
If the file you want to play is wav files, try this.
var player = new System.Media.SoundPlayer("c:\\tes.wav");
player.Play();
For myself I wrote this SounceController, hope it help:
using System.Windows.Media; // add reference to system.windows.presentation.
using System;
using System.IO;
public class SoundController
{
private bool isPlaying;
private MediaPlayer player;
public SoundController()
{
player = new MediaPlayer();
}
~SoundController()
{
player = null;
}
public void Play(string path)
{
if (!File.Exists(path) || isPlaying)
return;
isPlaying = true;
player.Open(new Uri(path));
player.Play();
}
public void Stop()
{
if (isPlaying)
{
isPlaying = false;
player.Stop();
}
}
}
I recommend you use PInvoke To play sound using winmm.dll
first of all import System.Runtime.InteropServices namespace in to your project.
using System.Runtime.InteropServices;
Then in your class you will have
[DllImport("winmm.dll")]
static extern Int32 mciSendString(string command, StringBuilder buffer, int bufferSize, IntPtr hwndCallback);
public void Play(string path ,string name)
{
// Open
mciSendString($#"open {path} type waveaudio alias {name}", null, 0, IntPtr.Zero);
// Play
mciSendString($#"play {name}", null, 0, IntPtr.Zero);
}
You can play the sound sending correct path of wave file with name. . given name does not need to be the same name of wave file.for example:
Play(#"C:\soundeffect.wav", "soundEffect1");
Usually sound effects are played simultaneously. you can call this method several times to play several files simultaneously.
Play(#"C:\soundeffect1.wav", "soundEffect1");
Play(#"C:\soundeffect2.wav", "soundEffect2");
Play(#"C:\soundeffect3.wav", "soundEffect3");
How can I figure out if Windows is currently playing any sounds through the primary audio device? I need to know, so that I can make my program automatically adjust its volume.
You could use CSCore.
Download it right here -> http://cscore.codeplex.com/
Paste these lines on a console project.
using System;
using CSCore.CoreAudioAPI;
namespace AudioDetector
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(IsAudioPlaying(GetDefaultRenderDevice()));
Console.ReadLine();
}
public static MMDevice GetDefaultRenderDevice()
{
using (var enumerator = new MMDeviceEnumerator())
{
return enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Console);
}
}
public static bool IsAudioPlaying(MMDevice device)
{
using (var meter = AudioMeterInformation.FromDevice(device))
{
return meter.PeakValue > 0;
}
}
}
}
Play a music be it on YouTube, Music Player, etc...
Run the program.
It automatically notifies(true/false) if there is an audio currently being played or not.
You may need to mess around with mixer controls.
Mixer Control
These may help ya out too.
Measure speaker volume by recording playing sound with microphone
Using p/invoke and win-api to monitor audio line-in (C#)