SoundPlayer adjustable volume - c#

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.

Related

How to get data from 'AudioSource.time' in Unity script?

I am making a Music Player app for Android in Unity3d. For show_currentPlayTime() function, I want to get AS.time value to show current playTime. For seek() function, I want to set AS.time value to get to that specific point of AudioClip. But, the problem is that AS.time is giving me 0.
I have tried setting AudioClip in AudioSource. It works that way, but the audio becomes distorted and shows abnormal behavior.
Variable Declaration:
public AudioSource AS;
[Range(0.0f, 1.0f)]
public Slider Volume;
public Slider slider;
bool isPlaying;
public List<AudioClip> AC = new List<AudioClip>();
int currentSong = 0;
Play Function:
public void Play()
{
AS.Stop();
AS.PlayOneShot(AC[currentSong]);
//AS.clip = AC[currentSong]; ---
//AS.Play(); ---
//AS.clip = AC[currentSong]; ---
//AS.PlayOneShot(AS.clip); ---
clipInfo.text = AC[currentSong].name;
Debug.Log(AC[currentSong].name);
CancelInvoke();
Invoke("Next", AC[currentSong].length);
isPlaying = true;
}
The program runs with using --- lines, in above code, but with that, the audio becomes distorted.
Music Seek function:
public void MusicSlider()
{
AS.time = AC[currentSong].length * slider.value;
slider.value = AS.time / AC[currentSong].length;
Debug.Log(AS.time);
}
AS.time gives me value = 0.
The AudioSource.Stop function stops the currently set Audio clip from playing
so you shouldn't be using PlayOneShot since this doesn't assign the clip value and isn't stopped but played parallel. It is usually more used for playing soundeffects which may occure at the same time.
From AudioSource
You can play a single audio clip using Play, Pause and Stop You can also adjust its volume while playing using the volume property, or seek using time. Multiple sounds can be played on one AudioSource using PlayOneShot.
AudioSource.time from the examples also only seems to work using Play instead of PlayOneShot for the same reason.
In the commented code you are also mixing both Play and PlayOneShot. I guess what you called distorted is actually the clip playing twice at the same time. Your code should rather simply be
public void Play()
{
AS.Stop();
AS.clip = AC[currentSong];
AS.Play();
clipInfo.text = AC[currentSong].name;
Debug.Log(AC[currentSong].name);
// Don't know ofcourse what those methods do...
CancelInvoke();
Invoke("Next", AC[currentSong].length);
isPlaying = true;
}

The name 'Microphone' does not exist in the current context unity

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;

Play Sounds in a Visual Studio Application

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 do I figure out if Windows is currently playing any sounds?

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#)

Change The Volume in System.Media.SoundPlayer

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.

Categories