Skip to content

Commit

Permalink
Added RecordWithSpecificFormat sample. See #121 and #124.
Browse files Browse the repository at this point in the history
  • Loading branch information
filoe committed Aug 2, 2016
1 parent baea079 commit ed62eb2
Show file tree
Hide file tree
Showing 4 changed files with 276 additions and 0 deletions.
13 changes: 13 additions & 0 deletions CSCore.sln
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSCoreWaveform", "Samples\C
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BiQuadFilterSample", "Samples\BiQuadFilterSample\BiQuadFilterSample.csproj", "{F8733117-DA1D-40DC-AEF8-98051B86E219}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RecordWithSpecificFormat", "Samples\RecordWithSpecificFormat\RecordWithSpecificFormat.csproj", "{E0198A08-AAA8-4A76-B096-BBE72DA4F93B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -226,6 +228,16 @@ Global
{F8733117-DA1D-40DC-AEF8-98051B86E219}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{F8733117-DA1D-40DC-AEF8-98051B86E219}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{F8733117-DA1D-40DC-AEF8-98051B86E219}.Release|Win32.ActiveCfg = Release|Any CPU
{E0198A08-AAA8-4A76-B096-BBE72DA4F93B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E0198A08-AAA8-4A76-B096-BBE72DA4F93B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E0198A08-AAA8-4A76-B096-BBE72DA4F93B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{E0198A08-AAA8-4A76-B096-BBE72DA4F93B}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{E0198A08-AAA8-4A76-B096-BBE72DA4F93B}.Debug|Win32.ActiveCfg = Debug|Any CPU
{E0198A08-AAA8-4A76-B096-BBE72DA4F93B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E0198A08-AAA8-4A76-B096-BBE72DA4F93B}.Release|Any CPU.Build.0 = Release|Any CPU
{E0198A08-AAA8-4A76-B096-BBE72DA4F93B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{E0198A08-AAA8-4A76-B096-BBE72DA4F93B}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{E0198A08-AAA8-4A76-B096-BBE72DA4F93B}.Release|Win32.ActiveCfg = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -246,5 +258,6 @@ Global
{000B0B0B-A12D-4EED-A261-7F95422E386A} = {41D1D336-13B2-488B-8A85-C0F744035F8B}
{529DEB01-14A3-4FEC-AD89-6D4D0DC433C3} = {41D1D336-13B2-488B-8A85-C0F744035F8B}
{F8733117-DA1D-40DC-AEF8-98051B86E219} = {41D1D336-13B2-488B-8A85-C0F744035F8B}
{E0198A08-AAA8-4A76-B096-BBE72DA4F93B} = {41D1D336-13B2-488B-8A85-C0F744035F8B}
EndGlobalSection
EndGlobal
167 changes: 167 additions & 0 deletions Samples/RecordWithSpecificFormat/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
using System;
using System.Diagnostics;
using System.Linq;
using CSCore;
using CSCore.Codecs.WAV;
using CSCore.CoreAudioAPI;
using CSCore.SoundIn;
using CSCore.Streams;

namespace RecordWithSpecificFormat
{
class Program
{
// ReSharper disable once UnusedParameter.Local
static void Main(string[] args)
{
//choose the capture mode
Console.WriteLine("Select capturing mode:");
Console.WriteLine("- 1: Capture");
Console.WriteLine("- 2: LoopbackCapture");

CaptureMode captureMode = (CaptureMode)ReadInteger(1, 2);
DataFlow dataFlow = captureMode == CaptureMode.Capture ? DataFlow.Capture : DataFlow.Render;

//---

//select the device:
var devices = MMDeviceEnumerator.EnumerateDevices(dataFlow, DeviceState.Active);
if (!devices.Any())
{
Console.WriteLine("No devices found.");
return;
}

Console.WriteLine("Select device:");
for (int i = 0; i < devices.Count; i++)
{
Console.WriteLine("- {0:#00}: {1}", i, devices[i].FriendlyName);
}
int selectedDeviceIndex = ReadInteger(Enumerable.Range(0, devices.Count).ToArray());
var device = devices[selectedDeviceIndex];

//--- choose format
Console.WriteLine("Enter sample rate:");
int sampleRate;
do
{
sampleRate = ReadInteger();
if (sampleRate >= 100 && sampleRate <= 200000)
break;
Console.WriteLine("Must be between 1kHz and 200kHz.");
} while (true);

Console.WriteLine("Choose bits per sample (8, 16, 24 or 32):");
int bitsPerSample = ReadInteger(8, 16, 24, 32);

//note: this sample does not support multi channel formats like surround 5.1,...
//if this is required, the DmoChannelResampler class can be used
Console.WriteLine("Choose number of channels (1, 2):");
int channels = ReadInteger(1, 2);

//---

//start recording

//create a new soundIn instance
using (WasapiCapture soundIn = captureMode == CaptureMode.Capture
? new WasapiCapture()
: new WasapiLoopbackCapture())
{
//optional: set some properties
soundIn.Device = device;
//...

//initialize the soundIn instance
soundIn.Initialize();

//create a SoundSource around the the soundIn instance
//this SoundSource will provide data, captured by the soundIn instance
SoundInSource soundInSource = new SoundInSource(soundIn) {FillWithZeros = false};

//create a source, that converts the data provided by the
//soundInSource to any other format
//in this case the "Fluent"-extension methods are being used
IWaveSource convertedSource = soundInSource
.ChangeSampleRate(sampleRate) // sample rate
.ToSampleSource()
.ToWaveSource(bitsPerSample); //bits per sample

//channels...
using (convertedSource = channels == 1 ? convertedSource.ToMono() : convertedSource.ToStereo())
{

//create a new wavefile
using (WaveWriter waveWriter = new WaveWriter("out.wav", convertedSource.WaveFormat))
{

//register an event handler for the DataAvailable event of
//the soundInSource
//Important: use the DataAvailable of the SoundInSource
//If you use the DataAvailable event of the ISoundIn itself
//the data recorded by that event might won't be available at the
//soundInSource yet
soundInSource.DataAvailable += (s, e) =>
{
//read data from the converedSource
//important: don't use the e.Data here
//the e.Data contains the raw data provided by the
//soundInSource which won't have your target format
byte[] buffer = new byte[convertedSource.WaveFormat.BytesPerSecond / 2];
int read;
//keep reading as long as we still get some data
//if you're using such a loop, make sure that soundInSource.FillWithZeros is set to false
while ((read = convertedSource.Read(buffer, 0, buffer.Length)) > 0)
{
//write the read data to a file
// ReSharper disable once AccessToDisposedClosure
waveWriter.Write(buffer, 0, read);
}
};

//we've set everything we need -> start capturing data
soundIn.Start();

Console.WriteLine("Capturing started ... press any key to stop.");
Console.ReadKey();

soundIn.Stop();
}
}
}

Process.Start("out.wav");
}

private static int ReadInteger(params int[] validValues)
{
int value;

do
{
value = ReadInteger();
if (validValues == null || validValues.Any(x => x == value))
return value;
Console.WriteLine("Invalid value");
} while (true);
}

private static int ReadInteger()
{
int value;
while (!Int32.TryParse(Console.ReadLine(), out value))
{
Console.WriteLine("Invalid value");
}
return value;
}

enum CaptureMode
{
Capture = 1,
// ReSharper disable once UnusedMember.Local
LoopbackCapture = 2
}
}
}
36 changes: 36 additions & 0 deletions Samples/RecordWithSpecificFormat/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RecordWithSpecificFormat")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RecordWithSpecificFormat")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("37b5903a-13ba-4b28-a98b-34697339cdd0")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
60 changes: 60 additions & 0 deletions Samples/RecordWithSpecificFormat/RecordWithSpecificFormat.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{E0198A08-AAA8-4A76-B096-BBE72DA4F93B}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>RecordWithSpecificFormat</RootNamespace>
<AssemblyName>RecordWithSpecificFormat</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\CSCore\CSCore.csproj">
<Project>{c3dccfe3-dd3f-4eee-849b-33e355b1e064}</Project>
<Name>CSCore</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

0 comments on commit ed62eb2

Please sign in to comment.