New! Alvas.Audio.Core

   Alvas.Audio

Stand with Ukraine!
Alvas.Net - .Net developers toolbox
  Overview    News    Articles    How to..    Samples    Videos    Order    Free Trial    Demo       PR    PAD  

Questions about Alvas.Audio [Download Alvas.Audio tips in PDF]

1. Is it possible to merge several audio (wave) files that I have on disk and produce a single audio wave file?
2. I want to read an existing wav file, change the format then write it back out.
3. If I buy Single License for Alvas.Audio, will there be no 'about window' deployed on the customers apllication whenever the application is started?
4. When we on windows 7 64-bit try to create a PlayerEx instance (as in: m_player = new PlayerEx() ) it throws an exception:
5. Is the runtime license free?
6. Do you provide some c# code with the classes?
7. I would like to know under what .Net language is the Audio application written?
8. Can you please confirm that if I buy a single user license for Alvas Suite, that it also includes Alvas.Audio?
9. Can we use Alvas.Audio for Pocket PC applications?
10. It appears to be necessary to select input and output devices. I would like to simply use the default devices that the user has selected on the control panel. Is this possible?
11. I need to be able to convert Dialogic files to MP3
12. Can you send me the complete list of all audio formats that can be converted FROM and converted TO using Alvas.Audio?
13. I want to decode a GSM-stream, but after a quick glance in the example-code and at Alvas.Audio.chm I can't really see how to do that.
14. I'm using the Alvas.Audio.dll, and i'm trying to play 2 wav's at the same time (I don't want the first one to stop when the second one begins). How can I make this happen?
15. Is this control suitable for use in MC++ Windows forms projects?
16. Would your audio compenent be suitable for Voip, would it decode and encode fast enough to keep latency at a minimum. Has it been used in this type of environment.
17. Can I use your audio toolkit to extract portions of a wav file to a new wav file?
18. Have you tested the audio on Vista?
19. Is it possible to insert new recordings into existing WAV files?
20. What does a single license entitle us to do, and how does it affect sales of software produced that include Alvas.Audio.
21. How do I stop (not pause) audio that's allready playing in command?
22. I would like to use your audio control for VoIP. Record to memory (Speex) and send the data by UDP the receive from UDP and playback raw data. Would your control be suitable for this purpose?
23. Using either the WaveReader or Player(Ex) classes, is there anyway for me to tell how long (in seconds) a WAV file is?
24. I'm looking for a way via a web page to convert a saved Wav file to MP3. Will your code allow me to do so?
25. I just need to get the duration in MS for a file. This code will be on an ASP.NET website, so I want to instance your class, assign a file name (NOT PLAY THE FILE) and then just get the duration. Is this possible with your Alvas.Audio classes - if so, which class does it?
26. I am developing an application in VB.net 2.0, and i am looking for a library to transform u-law audio files into mp3. Could I get some sample code to help me get this to work?
27. Is it possible to default to a particular format on any machine (e.g. 'MP3, 20kbps, 11,025Hz, mono') without the user having to specify it? I need to default to a low quality mp3 format for speech recording and I don't want the user to have to select anything. I want to make it as simple as possible for them. Is it reliable to just iterate through the FormatTags and select the right one based on matching a string? Or will different client machines have different values/indexes for these tags?
28. I need to be able to convert from ADPCM 6khz 4-bit mono, ADPCM 8khz 4-bit mono, PCM8 8khz 8-but uLaw mono formats and standard formats such as WAV.
29. Must I pay a license for every deploy on my customer or only one for developer?
30. Reading / Writing of our VOX Files is not possibile.
31. Can you convert WAV files to the headerless formats like Dialogic VOX and PCM 8khz?
32. It can play from an array of doubles?
33. I was evaluating your product to use in an application for Asterisk(VOIP) solution, but I found there is no output support for SLINEAR. Do you plan to support this format? This would be a great option since there is no Windows application to make the conversion for Asterisk.
34. How to convert a wave file into an raw alaw 8Khz mono file?
35. We need to be able to essentially convert a wav file while adjusting its speed by a factor.
36. Does the Alvas.Audio library work with Terminal Services?
37. How to send audio stream in the browser?
38. How to Play big audio files?
39. Simple RecorderEx example
40. Simple PlayerEx example
41. Can you tell me whether the player will support playing Dialogic .vox (adpcm) format?
42. I expected that the RecorderEx.Data event would be raised whenever a buffer (size determined by BufferSize) was filled, but it's only raised on the half-second. Is there any way to reduce this?
43. How do I Boost the volume of an existing WAVE file - How can I make it louder?
44. Do you have any examples or sample applications that record directly to mp3?
45. Can Alvas.NET perform mp3 playing in C# with selected sound card. I have multiple sound card on my PC.
46. I would like to know if it is possible to record both line-in and line-out from a soundcard (full duplex).
47. Does Alvas.Audio support 64bit operating systems?
48. How can I check frequency (sample rate) of MP3 file? The only way I could find is to use FormatDetails struct and parse frequency out of it's FormatName property. However, I'm sure there are nicer way to achieve this :)
49. I am a newbie trying to recode MP3 file to a different bit rate/sample rate/mode. Like changing the Bit rate, Sample rate or changing from stereo to mono or their combination. I would really appreciate any help, with code if possible.
50. Can you give an example to convert a mp3 file from 320kbps bit rate, stereo, 44khz sample rate to 48kbps bit rate, mono, 22khz.
51. Our company needs audio control, which can record separately and independently right and left channel from stereo input. Has Alvas.Audio got such functionality?
52. How can I get higher quality when converting from .vox to .mp3.
53. Could you be more specific about adding the control to the toolbox.
54. After the file has been played I want to delete it, but I get an “access denied” error, because the file is in use. Is there a way to release the file from the DSReader (or PlayerEx) so that I can delete it?
55. I'm looking for .net a component like yours that can convert .wma to .mp3 - can it easily to that.
56. Does Alvas.Audio work with Windows 7 RTM?
57. Is it possible to increase/amplify the volume of mp3 file using Alvas.Audio library?
58. Is it possible to work directly on free licence file formats like Ogg Vorbis?
59. Can I convert an MP3 file to .VOX format?
60. I have a byte array of PCM audio. I would like to convert that to a byte array of GSM audio (and back). Would your Alvas.Audio library be able to do that?
61. Is there a way to use a specific codec? For example, say I install the lame.acm as part of my application installation. Then the user decides to installs other codecs for some reason. Can I specifically ensure that I use my specific codec?
62. We're having some troubles with big audio files when we attempt to convert them from mp3 to wav: System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
63. Can Alvas.Audio can detect silence detection?
64. I would like to be able to select the input device like Microphone or CD Audio when recording sound.
65. Does your audio control allow real time monitoring of the lenght of the recording? Basically while its recording, can I see position with the scroll bar?
66. Can your audio library playback Shoutcast or Icecast radio streams? I also need to extract metadata from stream.
67. First, can you jump to a specific spot in a wav file and start recording from there? Meaning could I record for say five seconds, then replay the sound, then jump to the middle of the recording and start recording again from there?
68. I'm listening to an internet radio station over my speakers, and I'd like to record what I hear, and directly to an mp3 file. Can your alvas.audio contol record 'what you hear'? If so, how?
69. I try to convert a file on my web page but the process get stuck. The web page seems like it tries to load something but won't go on. What can I do?
70. I'm trying to trial your software, building it into our web application but the trial version I have downloaded won't work in my web app as it keeps trying to pop up a 'nag screen' which causes the app to throw an error. Is there any way to turn this off?
71. We are evaluating your Alvas.Audio product for a .net server side mixer and aren't able to evaluate it completely since we keep getting this error: 'Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.' The error seems to come from the Alvas.Audio.AboutBox.ShowNagScreen, which I would guess has to do that we are running a demo. Is there any way of testing server side things without getting that error just to make sure that it works for our project?
72. When converting audio from Wav to Mp3 and NOT using the Wave2Mp3 function, do you always need to convert the wave data into PCM data before converting it to MP3? Is there a reason for doing that?
73. I have to connect to a SHOUTcast stream, take 5 seconds of the sound then detect if there is silence (no sound above -14db). Would you be so kind to provide us with some sample?
74. I have multiple audio tracks with nothing but music. I have multiple recorded voice tracks no longer than 2-3 seconds each. What I would like to do is 'overlay' a voice track onto an audio track at a specified time and output the results to a single file. E.g. Audio track is 2 minutes long, and I would like to insert the voice track at 23 seconds as well 1m 05 seconds and at 1m 40 seconds. Can Alvas.Audio accomplish this sort of task for me??
75. Effectively, I have a block of memory which contains A-law data and I want to play the data using vb.net. Can you provide some sample code on how I can achieve this with PlayerEx?
76. Can I use Alvas.Audio to play(stream) MP3 from the buffer of byte array. Please explain it with sample code in c#.
77. Is possible to mix to mix two audio file, using an offset to start playing one of them (for example, the first start playing and second plays after one second).
78. Have you added some support for simple audio efects like simple echo, reverb or distorsion or something like that.
79. How can I remove the first .5 of a second from mp3 file? I can get it to do a whole second, but I just need to remove the first half.
80. Is it possible to get the bit rate of an mp3? (I can see how to get sample rate, and bits per sample but not bit rate).
81. Can you player easily play looping sounds (like the My.Computer.Audio.Play(file,AudioPlayMode.BackgroundLoop)? A small VB.NET example would be appreciated.
82. Is it posiable to play from one file selected parts as if they were one seqwence with no pausing betwen. E.g play from the 10 sec for 5 sec and imidiatly from position 20 sec for 7 sec long?
83. I need to do audio recording on my web application ASP.Net. Can I use Alvas.Audio for these purposes?
84. Combine an AIF file with 2 seconds of silence with another AIF file, and write that out as a mono 112kbps MP3. Is it possible to provide me with a sample of how to do this?
85. I need the MP3 to be of 44.1khz sample rate. The source AIFF files are at 48k. I attempted to specify the mp3 format with 44.1khz, but then the AcmConverter constructor throws an exception 'It is not succeeded to open the stream of conversion of data' How can I perform a sample rate conversion as well?
86. Is it possible to create 100 milliseconds of 1k sine wave (at-1db) with this library?
87. I need a simple way to record audio and store it into a file. I'm not concerned with its format but rather with simplicity. I'm just trying to get a handle of it and would like to know if it is possible to have an example (as simple as possible) on how I can click a button to start recording and button to stop recording and save the recording to a file. can you help?
88. I have 10 wav files with the same format - CCITT u-Law, 8000 Hz, mono. How to merge them together using Alvas.Audio?
89. Has Alvas.Audio got the ability to convert from a WAV to the various MP3 bit rates (128,160,192,etc.)?
90. The application of our software is to capture speech and segment the audio files during natural pauses in speech. So, what I need to do is when someone stops speaking for say, 5 seconds, we would detect that, stop writing data, close the file, open a new one, and wait for sound to start back up before recording again.
91. Is it possible for converting any audio file format to wave audio file with 8kBit/sec compression?
92. I'm working with a couple different source formats now: * a ULAW encoded VOX file at 8 bits-per-sample, 8Khz, mono; * a PCM WAV file at 16 bits-per-sample, 8Khz, mono. Both need to end up as MP3 ... preferred format is 32kbps mono (24Khz).
93. Is it possible for converting any audio file to mp3?
94. How to convert a large Wave file to Mp3?
95. Can we draw Alvas.Audio object on C# form like other tools in .net?
96. I have a few ten wav files and want to amplify all of them (automatically) so that they can be played louder. The code must detect the file's current maximum sound level and then automatically bring them to maximum before clipping (optional, it can boost a few dB more beyond the Maximum level for clipping as assigned by user).
97. Is It possible to use headerless .vox audio file with 'G.711 Alaw' format for converting to mp3 in vb.net?
98. I need to extract the audio data from a FLV with C#
99. I have an a-law mono 8000 Hz wav which I am trying to convert into mp3… I am getting a pretty bad echo and wondered if there was a better way to convert? Perhaps this could be a problem with the bitrate of the mp3 being low (8K)? I didn’t see a way to make the MP3 encoder use a higher bitrate than the primary bitrate.
100. I want to change an audio file format into another. Specifically, I want to convert any audio file into 6khz, 16 bit, mono, PCM wav format.
101. I have a 10 second sound effect wave file. What I would like to do is take that file and repeat it n number of times and then save the longer WAV file to disk.
102. I want to play audio(wave) channels(R or L) separate.
103. I want to calculate the playing time of the file (ex: 00:05:32).
104. How to create a wave STREAM out of raw audio samples in C#?
105. How to programatically change the playback device in C#?
106. I want to detect the current volume for the default audio recording device of the current computer
107. How to convert AMR sound stream to PCM uncompressed stream in .NET
108. How to play mp3 files in C#?
109. What is the easiest way to convert a compressed wav file to an uncompressed wav file in C#?
110. I want to change an audio file format into another. Specifically, I want to convert any audio file into 6khz, 16 bit, mono, PCM wav format.
111. What is the best way to convert various audio formats to PCM? For example: mp3, wav, ogg, vox.
112. I have a stream of u-Law compressed PCM data I am extracting from a Camera, I need to play this out the speakers?
113. I need to mix two audio files. Audio 1 will be a static file and used to 'tag' Audio 2. To be clear I'm talking about an audio tag not an ID3 tag. 1) How can I repeat Audio 1 when mixed with Audio 2 so that the result is the same length as Audio 2? 2) Audio 2 will be an MP3 and I don't want to re-encode it and possibly reduce it's quality.
114. I need convert wma to mp3. It seems to be choking on larger wma's (20mb) or so. It throws an out of memory exception in the DsReader.ReadData function and size of the converted mp3 is twice that of the wma file. What parameter do I use to reduce the size?
115. How to programmatically mute the Windows XP Volume using C#?
116. Is there a way to set the microphone volume in C# (normally done in control panel -> audio -> advanced, go to recording, and then dragging the slider)?
117. Detecting audio silence in WAV files using C#
118. Getting duration of audio file C#
119. Covert a A-Law mono .vox file to .wav file in c# .net. Vox file encoding is: A-Law mono at 8000 HZ.
120. How to pass PCM 8bit audio data in Echo filter?
121. How to convert Dialogic adpcm vox file 6000 samples per second to wave gsm?
122. How can I play an MP3 from a memory stream in C#?
123. Is there a way to determine the duration of a wav file that's held in a MemoryStream?
124. How to add metadata to WAV file?
125. C# resample audio from 8khz to 44.1/48khz.
126. How to use Alvas.Audio to detect any sounds?
127. Extract wav file from video file
128. I’m trying to play Vox files, which are encoded in U-Law, byte order Little-endian, 1 channel, with a sample rate of 8kHz. These are raw files, so I need to be able to hard set these attributes for the files to play. Is this possible in your application?
129. I am having trouble converting a 6000 hz Vox file to a 16 kbit MP3.
130. I am designing a sound editor and i was wondering that while a song is playing using your software would it record anything that is playing on the sound card in Windows XP?
131. I have noticed is that when the faded in track is joined to another segment of track, there is a slight skip.
132. Could you send me a example how to convert IEEE Floating Point Audio (received the captured data as floating point) to WAV?
133. How to convert .wav to .aiff?
134. How to convert audio file to mp3 with specified bitrate?
135. Does anyone know a simple way of converting a mp4 file to an ogg file?
136. How to improve quality of the converted mp3-files from wav-files with low bitrate in VB?
137. How to play WAV audio file from Resources in c#?
138. How convert wav pcm 44100 to a-law 8bit mono in c#?
139. How to convert PCM 8 bit 8000 wav file to mp3?
140. Whether Alvas.Audio can play then received from ALAW BYTE[] from the network IN C#; Each byte[] has 160 bytes,Receiving 50 packets per second
141. Is there a way to check to see if there are any recording devices on the system. I was wondering if there is a way to first check if there are recording devices before calling the StartRecord method.
142. The sample code you sent below is working great. Is there a way to increase the quality of the final MP3 and if so, how would the code below change?
143. Can Alvas.Audio convert an MP3 to a wav file with this codec/format: Codec: IMA WAV ADPCM Channels: Mono Sample Rate: 8000 Hz Bits per sample: 16   If so, do you have any sample code for that?
144. The issue we have is that the original file is captured from a dialogic telephony card in 8k 8bit mono format and is low-quality audio with a lot of background noise. The mp3 file that Alvas.Audio creates by default is a lower quality file. Is there a way to improve that? We use Visual Basic.Net.

Answers

1. Is it possible to merge several audio (wave) files that I have on disk and produce a single audio wave file?

Yes, of course. If You want to join 2 files their formats should be identical. For Example You can join "CCITT u-Law 8 bit mono" with "CCITT u-Law 8 bit mono". Thus if You have "CCITT u-Law 16 bit mono" You have to convert it to "CCITT u-Law 8 bit mono" (use AudioCompressionManager.Convert method). Please see example below.

        private void Join()

        {

            string path = Application.StartupPath;

            WaveReader wr1 = new WaveReader(File.OpenRead(path + @"\one.wav"));

            IntPtr format = wr1.ReadFormat();

            byte[] data1 = wr1.ReadData();

            wr1.Close();

            WaveReader wr2 = new WaveReader(File.OpenRead(path + @"\two.wav"));

            byte[] data2 = wr2.ReadData();

            wr2.Close();

            WaveWriter ww = new WaveWriter(File.Create(path + @"\join.wav"), AudioCompressionManager.FormatBytes(format));

            ww.WriteData(data1);

            ww.WriteData(data2);

            ww.Close();

        }


Up

2. I want to read an existing wav file, change the format then write it back out.

        private void Convert()

        {

            WaveReader read = new WaveReader(File.OpenRead(@"g:\~data\123.wav"));

            IntPtr oldFormat = read.ReadFormat();

            WaveFormat wf = AudioCompressionManager.GetWaveFormat(oldFormat);

            byte[] oldData = read.ReadData();

            FormatDetails[] fdArr = AudioCompressionManager.GetFormatList(wf);

            IntPtr newFormat = fdArr[fdArr.Length - 1].FormatHandle;

            byte[] data = AudioCompressionManager.Convert(oldFormat, newFormat, oldData, true);

            WaveWriter write = new WaveWriter(File.OpenWrite(@"g:\~data\123_new.wav"),

            AudioCompressionManager.FormatBytes(newFormat));

            write.WriteData(data);

            write.Close();

            read.Close();

        }


Up

3. If I buy Single License for Alvas.Audio, will there be no 'about window' deployed on the customers apllication whenever the application is started?

Yes, of course. The 'about window' doesn't appear when You buy the product.

Up

4. When we on windows 7 64-bit try to create a PlayerEx instance (as in: m_player = new PlayerEx() ) it throws an exception:

System.TypeInitializerException
The type initializer for 'd' threw an exception.
   at Alvas.Audio.PlayerEx..ctor()
... 
Inner Exception:
System.TypeLoadException
Could not load type 'g' from assembly 
'Alvas.Audio, Version=X.X.XXXX.XXXXX, Culture=neutral, PublicKeyToken=b0b8e5d43e21ecb6' because it 
contains an object field at offset 20 that is incorrectly aligned or overlapped by a non-object field.
   at d..cctor()
You need change your project property "Project/ Properties.../Build/Platform Target" to "x86" and rebuild.
This problem is solved in the latest version of the library.

Up

5. Is the runtime license free?

Yes, the runtime license is free.

Up

6. Do you provide some c# code with the classes?

Yes, the source code is available in Team edition of the product.

Up

7. I would like to know under what .Net language is the Audio application written?

Controls are 100% native CLR compliant written in C# and can be used in C#, VB.Net and other .Net languages.

Up

8. Can you please confirm that if I buy a single user license for Alvas Suite, that it also includes Alvas.Audio?

Yes, of course. If You buy Alvas Suite it will include Alvas.Audio.

Up

9. Can we use Alvas.Audio for Pocket PC applications?

No, Alvas.Audio can't be used for Pocket PC applications.

Up

10. It appears to be necessary to select input and output devices. I would like to simply use the default devices that the user has selected on the control panel. Is this possible?

Yes, it is possible. You need to assign -1 to RecorderID. Example, recEx.RecorderID = -1;

Up

11. I need to be able to convert Dialogic files to MP3

     string voxFile = @"C:\AlvasAudio\8000.vox";

     string mp3File = @"C:\AlvasAudio\8000.mp3";

     Vox2Mp3(voxFile, 1, 16, 8000, mp3File);

     //-------

     private static void Vox2Mp3(string voxFile, short channels, short bitsPerSample, int samplesPerSec, string mp3File)

        {

           BinaryReader br = new BinaryReader(File.OpenRead(voxFile));

           MemoryStream pcmStream = new MemoryStream();

           IntPtr pcmFormat = AudioCompressionManager.GetPcmFormat(channels, bitsPerSample, samplesPerSec);

           WaveWriter ww = new WaveWriter(pcmStream, AudioCompressionManager.FormatBytes(pcmFormat));

           Vox.Vox2Wav(br, ww);

           br.Close();

           IntPtr mp3Format = AudioCompressionManager.GetCompatibleFormat(pcmFormat, AudioCompressionManager.MpegLayer3FormatTag);

           WaveReader wr = new WaveReader(pcmStream);

           byte[] pcmData = wr.ReadData();

           wr.Close();

           byte[] data = AudioCompressionManager.Convert(pcmFormat, mp3Format, pcmData, false);

           BinaryWriter bw = new BinaryWriter(File.Create(mp3File));

           bw.Write(data, 0, data.Length);

           ww.Close();

           bw.Close();

        }


Up

12. Can you send me the complete list of all audio formats that can be converted FROM and converted TO using Alvas.Audio?


Up

13. I want to decode a GSM-stream, but after a quick glance in the example-code and at Alvas.Audio.chm I can't really see how to do that.

To encode a GSM-stream You need to run AudioExCS.exe demo and select "audio format tag" GSM 6.10. To decode a GSM-stream You need to use the Conversion tab and select the file with GSM data...

Up

14. I'm using the Alvas.Audio.dll, and i'm trying to play 2 wav's at the same time (I don't want the first one to stop when the second one begins). How can I make this happen?

Instead of PlayerEx.AddData use PlayerEx.AddMixData.

Up

15. Is this control suitable for use in MC++ Windows forms projects?

Yes, Alvas.Audio is suitable for use in MC++ (with managed extension) .Net Windows forms projects. Requirements: .Net Framework v1.1 or later (also .NET v3.5)

Up

16. Would your audio compenent be suitable for Voip, would it decode and encode fast enough to keep latency at a minimum. Has it been used in this type of environment.

Yes, of course.

Up

17. Can I use your audio toolkit to extract portions of a wav file to a new wav file?

wr.ReadData(2, 1);

Up

18. Have you tested the audio on Vista?

Yes, of course.

Up

19. Is it possible to insert new recordings into existing WAV files?

Yes, you can insert audio data into existing WAV file.

Up

20. What does a single license entitle us to do, and how does it affect sales of software produced that include Alvas.Audio.

Single license allows one developer to use Alvas.Audio. If You have more developers in the project You need to purchase additional licenses. For example Team license is for 4 developers. Any kind of license gives You Royalty-Free redistribution rights with your applications.

Up

21. How do I stop (not pause) audio that's allready playing in command?

Please use playerEx.ClosePlayer() method.

Up

22. I would like to use your audio control for VoIP. Record to memory (Speex) and send the data by UDP the receive from UDP and playback raw data. Would your control be suitable for this purpose?


Up

23. Using either the WaveReader or Player(Ex) classes, is there anyway for me to tell how long (in seconds) a WAV file is?

Look at WaveReader.GetDurationInMS.

Up

24. I'm looking for a way via a web page to convert a saved Wav file to MP3. Will your code allow me to do so?

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using Alvas.Audio;

using System.IO;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        ConvertAudio();

    }

 

    private void ConvertAudio()

    {

        string webFile = @"D:\AudioCS\bin\Debug\_web.mp3";

        string pcmFile = @"D:\AudioCS\bin\Debug\_AudioCS.wav";

        using (WaveReader wr = new WaveReader(File.OpenRead(pcmFile)))

        {

            IntPtr pcmFormat = wr.ReadFormat();

            byte[] pcmData = wr.ReadData();

            WaveFormat wf = AudioCompressionManager.GetWaveFormat(pcmFormat);

            if (wf.wFormatTag != AudioCompressionManager.PcmFormatTag)//Decode if not PCM data

            {

                Decode2Pcm(ref pcmFormat, ref pcmData, ref wf);

            }

            IntPtr webFormat = AudioCompressionManager.GetCompatibleFormat(pcmFormat,

            AudioCompressionManager.MpegLayer3FormatTag);

            byte[] webData = AudioCompressionManager.Convert(pcmFormat, webFormat,

            pcmData, false);

            MemoryStream ms = new MemoryStream();

 

            using (WaveWriter ww = new WaveWriter(ms,

            AudioCompressionManager.FormatBytes(webFormat)))

            {

                ww.WriteData(webData);

                using (WaveReader wr2 = new WaveReader(ms))

                {

                    using (FileStream fs = File.OpenWrite(webFile))

                    {

                        wr2.MakeMP3(fs);

                    }

                }

            }

        }

    }

 

    private static void Decode2Pcm(ref IntPtr format, ref byte[] data, ref WaveFormat wf)

    {

        IntPtr formatPcm16Bit = IntPtr.Zero;

        byte[] dataPcm16Bit = null;

        AudioCompressionManager.ToPcm16Bit(format, data, ref formatPcm16Bit, ref dataPcm16Bit);

        wf = AudioCompressionManager.GetWaveFormat(formatPcm16Bit);

        format = formatPcm16Bit;

        data = dataPcm16Bit;

    }

}


Up

25. I just need to get the duration in MS for a file. This code will be on an ASP.NET website, so I want to instance your class, assign a file name (NOT PLAY THE FILE) and then just get the duration. Is this possible with your Alvas.Audio classes - if so, which class does it?

Yes. Please use

            string path = @"c:\test.wav";

            WaveReader wr = new WaveReader(File.OpenRead(path));

            int durationInMS = wr.GetDurationInMS();

            wr.Close();


Up

26. I am developing an application in VB.net 2.0, and i am looking for a library to transform u-law audio files into mp3. Could I get some sample code to help me get this to work?

        Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click

            Dim inFile As String = "path_to_your_file.wav"

            Dim outFile As String = "path_to_output_file.mp3"

            Convert(inFile, outFile)

        End Sub

 

        Public Sub Convert(ByVal inFile As String, ByVal outFile As String)

            Dim inFs As FileStream = File.OpenRead(inFile)

            Dim wr As WaveReader = New WaveReader(inFs)

            Dim inFormat As IntPtr = wr.ReadFormat()

            Dim inData As Byte() = wr.ReadData

            Dim pcmFormat As IntPtr = AudioCompressionManager.GetCompatibleFormat(inFormat, AudioCompressionManager.PcmFormatTag)

            Dim pcmData As Byte() = AudioCompressionManager.Convert(inFormat, pcmFormat, inData, False)

            Dim mp3Format As IntPtr = AudioCompressionManager.GetCompatibleFormat(pcmFormat, AudioCompressionManager.MpegLayer3FormatTag)

            Dim mp3Data As Byte() = AudioCompressionManager.Convert(pcmFormat, mp3Format, pcmData, False)

            Dim outFs As MemoryStream = New MemoryStream()

            Dim ww As WaveWriter = New WaveWriter(outFs, AudioCompressionManager.FormatBytes(mp3Format))

            ww.WriteData(mp3Data)

            Dim outWr As WaveReader = New WaveReader(outFs)

            outWr.MakeMP3(File.Create(outFile))

            ww.Close()

        End Sub


Up

27. Is it possible to default to a particular format on any machine (e.g. 'MP3, 20kbps, 11,025Hz, mono') without the user having to specify it? I need to default to a low quality mp3 format for speech recording and I don't want the user to have to select anything. I want to make it as simple as possible for them. Is it reliable to just iterate through the FormatTags and select the right one based on matching a string? Or will different client machines have different values/indexes for these tags?

        //---

        private static IntPtr GetFormat()

        {

            WaveFormat wf = new WaveFormat();

            wf.wFormatTag = AudioCompressionManager.MpegLayer3FormatTag;

            wf.nChannels = 1;

            wf.nSamplesPerSec = 11025;

            FormatDetails[] fdArr = AudioCompressionManager.GetFormatList(wf);

            foreach (FormatDetails fd in fdArr)

            {

                WaveFormat fdWf = AudioCompressionManager.GetWaveFormat(fd.FormatHandle);

                if (fdWf.nAvgBytesPerSec * 8 == 20000)

                {

                    return fd.FormatHandle;

                }

            }

            return IntPtr.Zero;

        }


Up

28. I need to be able to convert from ADPCM 6khz 4-bit mono, ADPCM 8khz 4-bit mono, PCM8 8khz 8-but uLaw mono formats and standard formats such as WAV.

Please see the code below for converting Your three sample audio files.

            Vox2Pcm(@"C:\AlvasAudio\8000.vox", @"C:\AlvasAudio\8000.wav", 8000);

            Vox2Pcm(@"C:\AlvasAudio\6000.vox", @"C:\AlvasAudio\6000.wav", 6000);

            uLaw(@"C:\AlvasAudio\8000.pcm", @"C:\AlvasAudio\8000.pcm.wav");

 

        //-------

        private static void uLaw(string inFile, string outFile)

        {

            WaveFormat wf = new WaveFormat();

            wf.nChannels = 1;

            wf.nSamplesPerSec = 8000;

            wf.wFormatTag = AudioCompressionManager.MuLawFormatTag;

            FormatDetails[] fdArr = AudioCompressionManager.GetFormatList(wf);

            IntPtr format = fdArr[0].FormatHandle;

            RawReader br = new RawReader(File.OpenRead(inFile), format);

            byte[] data = br.ReadData();

            br.Close();

            WaveWriter ww = new WaveWriter(File.Create(outFile),

            AudioCompressionManager.FormatBytes(format));

            ww.WriteData(data);

            ww.Close();

        }

 

        private static void Vox2Pcm(string inFile, string outFile, int samplesPerSec)

        {

            BinaryReader br = new BinaryReader(File.OpenRead(inFile));

            IntPtr format = AudioCompressionManager.GetPcmFormat(1, 16, samplesPerSec);

            WaveWriter ww = new WaveWriter(File.Create(outFile),

            AudioCompressionManager.FormatBytes(format));

            Vox.Vox2Wav(br, ww);

            br.Close();

            ww.Close();

        }


Up

29. Must I pay a license for every deploy on my customer or only one for developer?

You must pay a license for every developer in your team.

Up

30. Reading / Writing of our VOX Files is not possibile.


Up

31. Can you convert WAV files to the headerless formats like Dialogic VOX and PCM 8khz?

Please see code for Wav2Vox with resample

            Wav2Vox(@"C:\AlvasAudio\6000.wav", @"C:\AlvasAudio\6000.wav.vox", 8000);

 

 

        private static void Wav2Vox(string inFile, string outFile, int samplesPerSec)

        {

            WaveReader wr = new WaveReader(File.OpenRead(inFile));

            IntPtr format = wr.ReadFormat();

            byte[] data = wr.ReadData();

            wr.Close();

            WaveFormat wf = AudioCompressionManager.GetWaveFormat(format);

            if (wf.wFormatTag != AudioCompressionManager.PcmFormatTag)//Decode if not PCM data

            {

                Decode2Pcm(ref format, ref data, ref wf);

            }

            if (wf.nSamplesPerSec != samplesPerSec)

            {

                Resample(ref format, ref data, ref wf, samplesPerSec);

            }

            BinaryWriter bw = new BinaryWriter(File.OpenWrite(outFile));

            BinaryReader br = new BinaryReader(new MemoryStream(data));

            Vox.Raw2Vox(br, bw, wf.wBitsPerSample);

            br.Close();

            bw.Close();

        }

 

        private static void Resample(ref IntPtr format, ref byte[] data, ref WaveFormat wf,

        int samplesPerSec)

        {

            IntPtr outFormat = AudioCompressionManager.GetPcmFormat(wf.nChannels, wf.wBitsPerSample, samplesPerSec);

            byte[] outData = AudioCompressionManager.Resample(format, data, outFormat);

            format = outFormat;

            data = outData;

            wf = AudioCompressionManager.GetWaveFormat(outFormat);

        }

 

        private static void Decode2Pcm(ref IntPtr format, ref byte[] data, ref WaveFormat wf)

        {

            IntPtr formatPcm16Bit = IntPtr.Zero;

            byte[] dataPcm16Bit = null;

            AudioCompressionManager.ToPcm16Bit(format, data, ref formatPcm16Bit, ref dataPcm16Bit);

            wf = AudioCompressionManager.GetWaveFormat(formatPcm16Bit);

            format = formatPcm16Bit;

            data = dataPcm16Bit;

        }


Up

32. It can play from an array of doubles?

        PlayerEx pl = new PlayerEx();

 

        private static void PlayArray(PlayerEx pl)

        {

            double fs = 8000; // sample freq

            double freq = 1000; // desired tone

            short[] mySound = new short[4000];

            for (int i = 0; i < 4000; i++)

            {

                double t = (double)i / fs; // current time

                mySound[i] = (short)(Math.Cos(t * freq) * (short.MaxValue));

            }

            IntPtr format = AudioCompressionManager.GetPcmFormat(1, 16, (int)fs);

            pl.OpenPlayer(format);

            byte[] mySoundByte = new byte[mySound.Length * 2];

            Buffer.BlockCopy(mySound, 0, mySoundByte, 0, mySoundByte.Length);

            pl.AddData(mySoundByte);

            pl.StartPlay();

        }


Up

33. I was evaluating your product to use in an application for Asterisk(VOIP) solution, but I found there is no output support for SLINEAR. Do you plan to support this format? This would be a great option since there is no Windows application to make the conversion for Asterisk.

Alvas.Audio supports SLINEAR files. See code below.

            Wav2Sln(@"C:\AlvasAudio\obrigada.wav", @"C:\AlvasAudio\obrigada.sln");

        //---

        private static void Wav2Sln(string inFile, string outFile)

        {

            IntPtr newFormat = AudioCompressionManager.GetPcmFormat(1, 16, 8000);

            WaveReader wr = new WaveReader(File.OpenRead(inFile));

            IntPtr oldFormat = wr.ReadFormat();

            byte[] data = wr.ReadData();

            wr.Close();

            byte[] buffer = AudioCompressionManager.Convert(oldFormat, newFormat, data, false);

            using (RawWriter bw = new RawWriter(File.Create(outFile)))

            {

                bw.WriteData(buffer);

            }

        }


Up

34. How to convert a wave file into an raw alaw 8Khz mono file?

            string pcmFile = @"C:\AlvasAudio\obrigada.wav";

            string alawFile = @"C:\AlvasAudio\obrigada.alaw";

            Pcm2ALaw(pcmFile, alawFile);

        //---

        private static void Pcm2ALaw(string wavFile, string alawFile)

        {

            WaveReader wr = new WaveReader(File.OpenRead(wavFile));

            IntPtr format = wr.ReadFormat();

            byte[] data = wr.ReadData();

            wr.Close();

            WaveFormat wfAlaw = new WaveFormat();

            wfAlaw.wFormatTag = AudioCompressionManager.ALawFormatTag;

            wfAlaw.nChannels = 1;

            wfAlaw.nSamplesPerSec = 8000;

            FormatDetails[] fdArr = AudioCompressionManager.GetFormatList(wfAlaw);

            WaveFormat wf = AudioCompressionManager.GetWaveFormat(format);

            if (wf.wFormatTag != AudioCompressionManager.PcmFormatTag)//Decode if not PCM data

            {

                Decode2Pcm(ref format, ref data, ref wf);

            }

            if (wf.nSamplesPerSec != wfAlaw.nSamplesPerSec || wf.nChannels != wfAlaw.nChannels)

            {

                Resample(ref format, ref data, ref wf, wfAlaw.nSamplesPerSec, wfAlaw.nChannels);

            }

 

            byte[] buffer = AudioCompressionManager.Convert(format, fdArr[0].FormatHandle, data, false);

            RawWriter bw = new RawWriter(File.Create(alawFile));

            bw.WriteData(buffer);

            bw.Close();

        }

 

        private static void Resample(ref IntPtr format, ref byte[] data, ref WaveFormat wf, int samplesPerSec, short channels)

        {

            IntPtr newFormat = AudioCompressionManager.GetPcmFormat(channels, wf.wBitsPerSample, samplesPerSec);

            byte[] buffer = AudioCompressionManager.Resample(format, data, newFormat);

            format = newFormat;

            wf = AudioCompressionManager.GetWaveFormat(newFormat);

            data = buffer;

        }

 

        private static void Decode2Pcm(ref IntPtr format, ref byte[] data, ref WaveFormat wf)

        {

            IntPtr formatPcm16Bit = IntPtr.Zero;

            byte[] dataPcm16Bit = null;

            AudioCompressionManager.ToPcm16Bit(format, data, ref formatPcm16Bit, ref dataPcm16Bit);

            wf = AudioCompressionManager.GetWaveFormat(formatPcm16Bit);

            format = formatPcm16Bit;

            data = dataPcm16Bit;

        }


Up

35. We need to be able to essentially convert a wav file while adjusting its speed by a factor.

//two times as quickly

AudioCompressionManager.ChangeSpeed(@"g:\AlvasAudio\obrigada.wav", @"g:\AlvasAudio\obrigada1.wav", 50);

//two times as slowly

AudioCompressionManager.ChangeSpeed(@"g:\AlvasAudio\obrigada.wav", @"g:\AlvasAudio\obrigada2.wav", 200);


Up

36. Does the Alvas.Audio library work with Terminal Services?

Due to the way audio drivers/codecs are remapped using TS with Windows 2000, the library will not work through TS when connecting to a Windows 2000 Server. It works fine from the console.

Up

37. How to send audio stream in the browser?

    public static void ResponseAudioStream(HttpResponse Response, string voxFile, int samplesPerSec)

    {

        BinaryReader br = new BinaryReader(File.OpenRead(voxFile));

        MemoryStream pcmStream = new MemoryStream();

 

        IntPtr pcmFormat = AudioCompressionManager.GetPcmFormat(1, 16, samplesPerSec);

        WaveWriter ww = new WaveWriter(pcmStream, AudioCompressionManager.FormatBytes(pcmFormat));

        Vox.Vox2Wav(br, ww);

        WaveReader wr = new WaveReader(pcmStream);

 

        byte[] pcmData = pcmStream.ToArray();

 

        br.Close();

        ww.Close();

        wr.Close();

        pcmStream.Close();

 

        Response.ContentType = "audio/x-wav";

        Response.BinaryWrite(pcmData);

        Response.End();

    }


Up

38. How to Play big audio files?

        private void btnPlay_Click(object sender, EventArgs e)

        {

            StartPlay(File.OpenRead(@"c:\audio\big.wav"));

        }

 

        public MainForm()

        {

            InitializeComponent();

            playEx.Done += new PlayerEx.DoneEventHandler(playEx_Done);

        }

 

        void playEx_Done(object sender, DoneEventArgs e)

        {

            ReadData();

        }

 

        private PlayerEx playEx = new PlayerEx();

        private WaveReader wr = null;

        private int pos = 0;

        private int seconds = 5;

        private int len = 0;

 

        public void StartPlay(Stream _stream)

        {

            if (playEx.State == DeviceState.Paused)

            {

                playEx.ResumePlay();

            }

            else

            {

                pos = 0;

                wr = new WaveReader(_stream);

                len = wr.GetDurationInMS() / 1000;

                IntPtr format = wr.ReadFormat();

                playEx.OpenPlayer(format);

                ReadData();

                playEx.StartPlay();

            }

        }

 

        private void ReadData()

        {

            if (pos <= len)

            {

                byte[] data = wr.ReadData(pos, seconds);

                pos += seconds;

                playEx.AddData(data);

            }

        }


Up

39. Simple RecorderEx example

using System;

using System.Windows.Forms;

using Alvas.Audio;

using System.IO;

 

namespace SimpleRecorder

{

    public partial class RecorderForm : Form

    {

        public RecorderForm()

        {

            InitializeComponent();

            Init();

        }

 

        private void Init()

        {

            btnStop.Enabled = false;

            rex = new RecorderEx();

            IntPtr pcmFormat = AudioCompressionManager.GetPcmFormat(1, 16, 44100);

            rex.Format = pcmFormat;//AudioCompressionManager.GetCompatibleFormat(pcmFormat, AudioCompressionManager.Gsm610FormatTag);

            rex.Open += new EventHandler(rex_Open);

            rex.Data += new RecorderEx.DataEventHandler(rex_Data);

            rex.Close += new EventHandler(rex_Close);

        }

 

        void rex_Close(object sender, EventArgs e)

        {

            ww.Close();

            ww = null;

        }

 

        void rex_Data(object sender, DataEventArgs e)

        {

            ww.WriteData(e.Data);

        }

 

        void rex_Open(object sender, EventArgs e)

        {

            if (ww != null)

            {

                ww.Close();

            }

            string fileName = Path.ChangeExtension(Application.ExecutablePath, ".wav");

            ww = new WaveWriter(File.Create(fileName),

                AudioCompressionManager.FormatBytes(rex.Format));

        }

 

        private RecorderEx rex;

        private WaveWriter ww;

 

        private void btnRec_Click(object sender, EventArgs e)

        {

            rex.StartRecord();

            EnableButtons();

        }

 

        private void EnableButtons()

        {

            btnStop.Enabled = !btnStop.Enabled;

            btnRec.Enabled = !btnRec.Enabled;

        }

 

        private void btnStop_Click(object sender, EventArgs e)

        {

            rex.StopRecord();

            EnableButtons();

        }

    }

}


Up

40. Simple PlayerEx example

using System;

using System.Windows.Forms;

using Alvas.Audio;

using System.IO;

 

namespace SimpleRecorder

{

    public partial class PlayerForm : Form

    {

        public PlayerForm()

        {

            InitializeComponent();

        }

 

        private PlayerEx plex = new PlayerEx();

 

        private void Play(string fileName)

        {

            using (WaveReader wr = new WaveReader(File.OpenRead(fileName)))

            {

                IntPtr format = wr.ReadFormat();

                byte[] data = wr.ReadData();

                plex.OpenPlayer(format);

                plex.AddData(data);

            }

            plex.StartPlay();

        }

 

        private void btnPlay_Click(object sender, EventArgs e)

        {

            Play(@"G:\AlvasAudio\gsm.wav");

        }

 

        private void btnStop_Click(object sender, EventArgs e)

        {

            if (plex.State != DeviceState.Closed)

            {

                plex.ClosePlayer();

            }

        }

 

    }

}


Up

41. Can you tell me whether the player will support playing Dialogic .vox (adpcm) format?

        private PlayerEx playEx = new PlayerEx();

 

        private void button1_Click(object sender, EventArgs e)

        {

            Stream str = Vox2Wav(@"c:\audio\8000.vox", 8000);

            WaveReader wr = new WaveReader(str);

            IntPtr format = wr.ReadFormat();

            byte[] data = wr.ReadData();

            str.Close();

            playEx.OpenPlayer(format);

            playEx.AddData(data);

            playEx.StartPlay();

        }

 

        private static Stream Vox2Wav(string voxFile, int samplesPerSec)

        {

            BinaryReader br = new BinaryReader(File.OpenRead(voxFile));

            IntPtr format = AudioCompressionManager.GetPcmFormat(1, 16, samplesPerSec);

            MemoryStream ms = new MemoryStream();

            WaveWriter ww = new WaveWriter(ms, AudioCompressionManager.FormatBytes(format));

            Vox.Vox2Wav(br, ww);

            br.Close();

            return ms;

        }


Up

42. I expected that the RecorderEx.Data event would be raised whenever a buffer (size determined by BufferSize) was filled, but it's only raised on the half-second. Is there any way to reduce this?

            recEx.AutoSizeBuffer = false;

            WaveFormat wf = AudioCompressionManager.GetWaveFormat(recEx.Format);

            recEx.BufferSize = AudioCompressionManager.Milliseconds2Bytes(wf, 100);//100 milliseconds


Up

43. How do I Boost the volume of an existing WAVE file - How can I make it louder?

        private static void ChangeVolume(string inFile, string outFile, int persent)

        {

            Stream inStream = File.OpenRead(inFile);

            Stream outStream = File.Create(outFile);

            WaveReader wr = new WaveReader(inStream);

            IntPtr format = wr.ReadFormat();

            byte[] data = wr.ReadData();

            wr.Close();

            byte[] buffer = AudioCompressionManager.ChangeVolume(format, data, persent);

            WaveWriter ww = new WaveWriter(outStream, AudioCompressionManager.FormatBytes(format));

            ww.WriteData(buffer);

            ww.Close();

        }


Up

44. Do you have any examples or sample applications that record directly to mp3?

        void recEx_DataMp3(object sender, DataEventArgs e)

        {

            mw.WriteData(e.Data);

        }

 

        private Mp3Writer mw;

        RecorderEx recEx = new RecorderEx();

 

        public void RecordMp3(string fileName)

        {

            recEx.Close += new EventHandler(recEx_CloseMp3);

            recEx.Data += new RecorderEx.DataEventHandler(recEx_DataMp3);

            FormatDetails[] fdArr = AudioCompressionManager.GetFormatList(AudioCompressionManager.MpegLayer3FormatTag);

            IntPtr format = fdArr[fdArr.Length - 1].FormatHandle;//GetMp3Format(2, 56, 24000);

            recEx.Format = format;

            mw = new Mp3Writer(File.Create(fileName));

            recEx.StartRecord();

        }


Up

45. Can Alvas.NET perform mp3 playing in C# with selected sound card. I have multiple sound card on my PC.

        private void PlayMp3()

        {

            playEx.PlayerID = 0;//select your sound card

            string fileName = @"c:\test.mp3";

            Mp3Reader br = new Mp3Reader(File.OpenRead(fileName));

            IntPtr format = br.ReadFormat();

            byte[] data = br.ReadData();

            br.Close();

            playEx.OpenPlayer(format);

            playEx.AddData(data);

            playEx.StartPlay();

        }


Up

46. I would like to know if it is possible to record both line-in and line-out from a soundcard (full duplex).

    public class RecordPlayForm : Form

    {

        public RecordPlayForm()

        {

            InitializeComponent();

            Init();

        }

 

        RecorderEx rex = new RecorderEx();

        PlayerEx play = new PlayerEx();

        IntPtr pcmFormat = AudioCompressionManager.GetPcmFormat(1, 16, 44100);

 

        private void Init()

        {

            rex.Data += new RecorderEx.DataEventHandler(rex_Data);

            rex.Open += new EventHandler(rex_Open);

            rex.Close += new EventHandler(rex_Close);

            rex.Format = pcmFormat;

        }

 

        void rex_Open(object sender, EventArgs e)

        {

            play.OpenPlayer(pcmFormat);

            play.StartPlay();

        }

 

        void rex_Close(object sender, EventArgs e)

        {

            play.ClosePlayer();

        }

 

        void rex_Data(object sender, DataEventArgs e)

        {

            play.AddData(e.Data);

        }

 

        private void btnRecordPlay_Click(object sender, EventArgs e)

        {

            rex.StartRecord();

        }

 

        private void btnStop_Click(object sender, EventArgs e)

        {

            rex.StopRecord();

        }

    }


Up

47. Does Alvas.Audio support 64bit operating systems?

Yes.

Up

48. How can I check frequency (sample rate) of MP3 file? The only way I could find is to use FormatDetails struct and parse frequency out of it's FormatName property. However, I'm sure there are nicer way to achieve this :)

Please use WaveFormat.nSamplesPerSec field.

Up

49. I am a newbie trying to recode MP3 file to a different bit rate/sample rate/mode. Like changing the Bit rate, Sample rate or changing from stereo to mono or their combination. I would really appreciate any help, with code if possible.

To change you need to decode mp3 to pcm. Edit pcm and encoding back to mp3. The example shows how to change the frequency to 8000.

        public void Mp3(string inFile)

        {

            //mp3 -> mp3 mono 8000 samples per second example

            int sps = 8000;

            short mono = 1;

            string outFile = inFile + ".mp3";

            Mp3Reader mr = new Mp3Reader(File.OpenRead(inFile));

            IntPtr formatMp3 = mr.ReadFormat();

            byte[] dataMp3 = mr.ReadData();

            mr.Close();

            IntPtr formatPcm = AudioCompressionManager.GetCompatibleFormat(formatMp3, AudioCompressionManager.PcmFormatTag);

            //mp3 -> pcm

            byte[] dataPcm = AudioCompressionManager.Convert(formatMp3, formatPcm, dataMp3, false);

            WaveFormat wf = AudioCompressionManager.GetWaveFormat(formatPcm);

            IntPtr formatPcm8000 = AudioCompressionManager.GetPcmFormat(mono, wf.wBitsPerSample, sps);

            //pcm -> pcm 8000 sps

            byte[] dataPcm8000 = AudioCompressionManager.Convert(formatPcm, formatPcm8000, dataPcm, false);

            //pcm8000 -> mp3 8000 sps

            IntPtr formatMp3_8000 = AudioCompressionManager.GetCompatibleFormat(formatPcm8000, AudioCompressionManager.MpegLayer3FormatTag);

            byte[] dataMp3_8000 = AudioCompressionManager.Convert(formatPcm8000, formatMp3_8000, dataPcm8000, false);

            Mp3Writer mw = new Mp3Writer(File.Create(outFile));

            mw.WriteData(dataMp3_8000);

            mw.Close();

        }


Up

50. Can you give an example to convert a mp3 file from 320kbps bit rate, stereo, 44khz sample rate to 48kbps bit rate, mono, 22khz.

        public void Mp3(string inFile)

        {

            //mp3 -> mp3 mono 48000 samples per second example

            int sps = 48000;

            short mono = 1;

            string outFile = inFile + ".mp3";

            Mp3Reader mr = new Mp3Reader(File.OpenRead(inFile));

            IntPtr formatMp3 = mr.ReadFormat();

            byte[] dataMp3 = mr.ReadData();

            mr.Close();

            IntPtr formatPcm = AudioCompressionManager.GetCompatibleFormat(formatMp3, AudioCompressionManager.PcmFormatTag);

            //mp3 -> pcm

            byte[] dataPcm = AudioCompressionManager.Convert(formatMp3, formatPcm, dataMp3, false);

            WaveFormat wf = AudioCompressionManager.GetWaveFormat(formatPcm);

            IntPtr formatPcm8000 = AudioCompressionManager.GetPcmFormat(mono, wf.wBitsPerSample, sps);

            //pcm -> pcm 48000 sps

            byte[] dataPcm8000 = AudioCompressionManager.Convert(formatPcm, formatPcm8000, dataPcm, false);

            //pcm8000 -> mp3 48000 sps

            IntPtr formatMp3_8000 = AudioCompressionManager.GetCompatibleFormat(formatPcm8000, AudioCompressionManager.MpegLayer3FormatTag);

            byte[] dataMp3_8000 = AudioCompressionManager.Convert(formatPcm8000, formatMp3_8000, dataPcm8000, false);

            Mp3Writer mw = new Mp3Writer(File.Create(outFile));

            mw.WriteData(dataMp3_8000);

            mw.Close();

        }


Up

51. Our company needs audio control, which can record separately and independently right and left channel from stereo input. Has Alvas.Audio got such functionality?

Yes, You can use AudioCompressionManager.SplitStereo method for split one stereo to 2 mono.

using System;

using Alvas.Audio;

using System.IO;

using System.Windows.Forms;

 

namespace ConvertMp3

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

            Init();

        }

 

        private void Init()

        {

            rex.Open += new EventHandler(rex_Open);

            rex.Data += new RecorderEx.DataEventHandler(rex_Data);

            rex.Close += new EventHandler(rex_Close);

        }

 

        void rex_Data(object sender, DataEventArgs e)

        {

            IntPtr formatMono = IntPtr.Zero;

            AudioCompressionManager.SplitStereo(rex.Format, e.Data, ref

formatMono,

                ref leftData, ref rightData);

            if (ww1 == null)

            {

                byte[] formatBytes =

AudioCompressionManager.FormatBytes(formatMono);

                ww1 = new WaveWriter(File.Create("left.wav"), formatBytes);

                ww2 = new WaveWriter(File.Create("right.wav"), formatBytes);

            }

            ww1.WriteData(leftData);

            ww2.WriteData(rightData);

        }

 

        void rex_Open(object sender, EventArgs e)

        {

        }

 

        void rex_Close(object sender, EventArgs e)

        {

            ww1.Close();

            ww2.Close();

            ww1 = null;

            ww2 = null;

        }

 

        RecorderEx rex = new RecorderEx();

        WaveWriter ww1;

        WaveWriter ww2;

        byte[] leftData = null;

        byte[] rightData = null;

 

        private void btnRecord_Click(object sender, EventArgs e)

        {

            rex.Format = AudioCompressionManager.GetPcmFormat(2, 16, 44100);

            rex.StartRecord();

        }

 

        private void btnStop_Click(object sender, EventArgs e)

        {

            rex.StopRecord();

        }

    }

}


Up

52. How can I get higher quality when converting from .vox to .mp3.

Vox2Mp3(@"c:\audio\files\8000.vox", 8000, 16000);

 

 

        private static void Vox2Mp3(string voxFile, int samplesPerSecFrom,

int samplesPerSecTo)

        {

            BinaryReader br = new BinaryReader(File.OpenRead(voxFile));

            MemoryStream pcmStream = new MemoryStream();

            IntPtr pcmFormat = AudioCompressionManager.GetPcmFormat(1, 16,

samplesPerSecFrom);

            WaveWriter ww = new WaveWriter(pcmStream,

AudioCompressionManager.FormatBytes(pcmFormat));

            Vox.Vox2Wav(br, ww);

            br.Close();

 

            WaveReader wr = new WaveReader(pcmStream);

            byte[] pcmData = wr.ReadData();

            wr.Close();

            IntPtr pcmFormat2 = AudioCompressionManager.GetPcmFormat(1, 16,

samplesPerSecTo);

            byte[] pcmData2 = AudioCompressionManager.Convert(pcmFormat,

pcmFormat2, pcmData, false);

 

            IntPtr mp3Format =

AudioCompressionManager.GetCompatibleFormat(pcmFormat2,

AudioCompressionManager.MpegLayer3FormatTag);

            byte[] data = AudioCompressionManager.Convert(pcmFormat2,

mp3Format, pcmData2, false);

            string mp3File = voxFile + ".mp3";

            Mp3Writer mw = new Mp3Writer(File.Create(mp3File));

            mw.WriteData(data);

            ww.Close();

            mw.Close();

        }


Up

53. Could you be more specific about adding the control to the toolbox.

Right-click on Toolbox, click "Add Tab" and enter "Alvas.Audio", click "Choose Items...", click "Browse..." and select Alvas.Audio.dll. Click "OK".

Up

54. After the file has been played I want to delete it, but I get an “access denied” error, because the file is in use. Is there a way to release the file from the DSReader (or PlayerEx) so that I can delete it?

DSReader.Close();

Up

55. I'm looking for .net a component like yours that can convert .wma to .mp3 - can it easily to that.

        private void WmaToMp3(string fileName)

        {

            DsReader dr = new DsReader(fileName);

            IntPtr format = dr.ReadFormat();

            IntPtr formatMp3 =

AudioCompressionManager.GetCompatibleFormat(format,

AudioCompressionManager.MpegLayer3FormatTag);

            byte[] data = dr.ReadData();

            dr.Close();

            byte[] dataMp3 = AudioCompressionManager.Convert(format,

formatMp3, data, false);

            Mp3Writer mw = new Mp3Writer(File.Create(fileName + ".mp3"));

            mw.WriteData(dataMp3);

            mw.Close();

        }


Up

56. Does Alvas.Audio work with Windows 7 RTM?

Yes

Up

57. Is it possible to increase/amplify the volume of mp3 file using Alvas.Audio library?

        public static void ChangeVolumeMp3(string inFile, string outFile)

        {

            Mp3Reader mr = new Mp3Reader(File.OpenRead(inFile));

            byte[] data =

AudioCompressionManager.ChangeVolume(mr.ReadFormat(), mr.ReadData(), 50);

            mr.Close();

            Mp3Writer mw = new Mp3Writer(File.Create(outFile));

            mw.WriteData(data);

            mw.Close();

        }


Up

58. Is it possible to work directly on free licence file formats like Ogg Vorbis?

Yes. You need only install "Ogg Vorbis ACM Codec" codec
http://www.free-codecs.com/download/Vorbis_Ogg_ACM.htm

Up

59. Can I convert an MP3 file to .VOX format?

        public static void Mp3ToVox(string mp3File, string voxFile)

        {

            int samplesPerSec = 8000;

            Mp3Reader mr = new Mp3Reader(File.OpenRead(mp3File));

            IntPtr format = mr.ReadFormat();

            byte[] data = mr.ReadData();

            mr.Close();

            IntPtr formatPcm = AudioCompressionManager.GetCompatibleFormat(format, AudioCompressionManager.PcmFormatTag);

            WaveFormat wfPcm = AudioCompressionManager.GetWaveFormat(formatPcm);

            byte[] dataPcm = AudioCompressionManager.Convert(format, formatPcm, data, false);

            if (wfPcm.nSamplesPerSec != samplesPerSec)

            {

                Resample(ref formatPcm, ref dataPcm, ref wfPcm, samplesPerSec);

            }

            BinaryWriter bw = new BinaryWriter(File.OpenWrite(voxFile));

            BinaryReader br = new BinaryReader(new MemoryStream(dataPcm));

            Vox.Raw2Vox(br, bw, wfPcm.wBitsPerSample);

            br.Close();

            bw.Close();

        }

 

        private static void Resample(ref IntPtr format, ref byte[] data, ref WaveFormat wf, int samplesPerSec)

        {

            IntPtr outFormat = AudioCompressionManager.GetPcmFormat(wf.nChannels, wf.wBitsPerSample, samplesPerSec);

            byte[] outData = AudioCompressionManager.Resample(format, data, outFormat);

            format = outFormat;

            data = outData;

            wf = AudioCompressionManager.GetWaveFormat(outFormat);

        }


Up

60. I have a byte array of PCM audio. I would like to convert that to a byte array of GSM audio (and back). Would your Alvas.Audio library be able to do that?

        private static void TestGsmPcm()

        {

            IntPtr formatPcm = AudioCompressionManager.GetPcmFormat(1, 16,

8000);

            byte[] dataPcm = null;//your pcm data

            IntPtr formatGsm;

            byte[] dataGsm;

            //pcm -> gsm

            Convert(formatPcm, dataPcm,

AudioCompressionManager.Gsm610FormatTag, out formatGsm, out dataGsm);

            //gsm -> pcm

            Convert(formatGsm, dataGsm,

AudioCompressionManager.PcmFormatTag, out formatPcm, out dataPcm);

        }

 

        private static void Convert(IntPtr formatIn, byte[] dataIn, short

formatTag, out IntPtr formatOut, out byte[] dataOut)

        {

            formatOut =

AudioCompressionManager.GetCompatibleFormat(formatIn, formatTag);

            dataOut = AudioCompressionManager.Convert(formatIn, formatOut,

dataIn, false);

        }


Up

61. Is there a way to use a specific codec? For example, say I install the lame.acm as part of my application installation. Then the user decides to installs other codecs for some reason. Can I specifically ensure that I use my specific codec?

        private void GetDriver()

        {

            foreach (DriverDetails dd in AudioCompressionManager.GetDriverList())

            {

                if (dd.LongName.Contains("{insert text here}"))

                {

                    int driverId = dd.Driver;

                    FormatDetails[] fd = AudioCompressionManager.GetFormatList(AudioCompressionManager.MpegLayer3FormatTag, driverId, true);

                    break;

                }

            };

        }


Up

62. We're having some troubles with big audio files when we attempt to convert them from mp3 to wav: System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.

        public static bool Mp3ToWav(string inFile, string outFile)

        {

            using (Mp3Reader mp3 = new Mp3Reader(File.OpenRead(inFile)))

            {

                try

                {

                    IntPtr mp3Format = mp3.ReadFormat();

                    IntPtr pcmFormat = AudioCompressionManager.GetCompatibleFormat(mp3Format, AudioCompressionManager.PcmFormatTag);

 

                    AcmConverter acm = new AcmConverter(mp3Format, pcmFormat, false);

                    int sec = 1000;

                    int i = 0;

                    using (WaveWriter ww = new WaveWriter(File.OpenWrite(outFile), AudioCompressionManager.FormatBytes(pcmFormat)))

                    {

                        while (true)

                        {

                            byte[] mp3Data = mp3.ReadData(i, sec);

                            if (mp3Data.Length == 0)

                            {

                                break;

                            }

                            byte[] pcmData = acm.Convert(mp3Data);

                            ww.WriteData(pcmData);

                            i += sec;

                        }

                        ww.Close();

                    }

                    mp3.Close();

                    GC.Collect();

                    return true;

                }

                catch (Exception ex)

                {

                    mp3.Close();

                    Console.WriteLine("\tCan not convert Mp3 to Wav, " + ex.ToString());

                    return false;

                }

            }

        }


Up

63. Can Alvas.Audio can detect silence detection?

Yes. Please see RecordPlay demo "skip silent"

Up

64. I would like to be able to select the input device like Microphone or CD Audio when recording sound.

Please see RecordPlay example

Up

65. Does your audio control allow real time monitoring of the lenght of the recording? Basically while its recording, can I see position with the scroll bar?

Yes. Please see RecordPlay demo

Up

66. Can your audio library playback Shoutcast or Icecast radio streams? I also need to extract metadata from stream.

Imports Alvas.Audio

 

Public Class MainForm

 

    Private Sub btnPlay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPlay.Click

        ReadRadio("http://www.wmph.org:7050/wmph64k")

    End Sub

 

    Private Sub btnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStop.Click

 

        If Not t Is Nothing AndAlso t.ThreadState = Threading.ThreadState.Running Then

            t.Abort()

            btnStop.Enabled = False

            btnPlay.Enabled = True

        End If

    End Sub

 

    Private plex As PlayerEx = New Alvas.Audio.PlayerEx(True)

    Private t As Threading.Thread

 

    Private Sub ReadRadio(ByVal StreamURL As String)

        btnStop.Enabled = True

        btnPlay.Enabled = False

        t = New System.Threading.Thread(New System.Threading.ParameterizedThreadStart(AddressOf ThreadProc))

        t.Start(StreamURL)

    End Sub

 

    Private Sub ThreadProc(ByVal StreamURL As Object)

        Dim WebReq As System.Net.HttpWebRequest = CType(System.Net.WebRequest.Create(StreamURL), System.Net.HttpWebRequest)

 

        Dim MyURI As New Uri(StreamURL)

 

        WebReq.Headers.Clear()

        WebReq.Timeout = 5000

        WebReq.Headers.Add("GET", MyURI.AbsolutePath & " HTTP/1.0")

        WebReq.UserAgent = "WinampMPEG/5.0"

        WebReq.Headers.Add("Icy-MetaData", "1")

        Dim WebRes As System.Net.WebResponse = WebReq.GetResponse()

        Dim oReader As System.IO.Stream = WebRes.GetResponseStream()

        Dim MetaInterval As Integer = WebRes.Headers("icy-metaint")

        Dim data(MetaInterval - 1) As Byte

        Dim b As Byte = 0

        Dim BlockCount As Integer

        Try

            While True

 

                b = oReader.ReadByte()

                If BlockCount = MetaInterval Then

                    If plex.State = DeviceState.Closed Then

                        Dim mr As Mp3Reader = New Mp3Reader(New IO.MemoryStream(data))

                        Dim format As IntPtr = mr.ReadFormat()

                        mr.Close()

                        plex.OpenPlayer(format)

                        plex.StartPlay()

                    End If

                    plex.AddData(data)

                    Dim MetaDataLength As Integer = b * 16

 

                    If MetaDataLength > 0 Then

                        Dim MetaArray(MetaDataLength - 1) As Byte

                        oReader.Read(MetaArray, 0, MetaDataLength)

                        Dim AEnc As New System.Text.ASCIIEncoding

 

                        Dim TempMetaData As String = AEnc.GetString(MetaArray)

 

                        'Trim it down

                        Dim StartPosition As Integer = TempMetaData.IndexOf("'") + 1

                        Dim EndPosition As Integer = TempMetaData.IndexOf("';", StartPosition)

                        TempMetaData = TempMetaData.Substring(StartPosition, EndPosition - StartPosition)

                        Console.WriteLine(TempMetaData)

                    End If

                    BlockCount = 0

                    Continue While

 

                Else

                    data(BlockCount) = b

                End If

 

                BlockCount = BlockCount + 1

            End While

        Finally

            oReader.Close()

            plex.ClosePlayer()

        End Try

    End Sub

 

    Private Sub Form1_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed

        btnStop.PerformClick()

    End Sub

End Class


Up

67. First, can you jump to a specific spot in a wav file and start recording from there? Meaning could I record for say five seconds, then replay the sound, then jump to the middle of the recording and start recording again from there?

Yes. Please see RecordPlay example

Up

68. I'm listening to an internet radio station over my speakers, and I'd like to record what I hear, and directly to an mp3 file. Can your alvas.audio contol record 'what you hear'? If so, how?

using System;

using System.Windows.Forms;

using Alvas.Audio;

using System.IO;

using System.Threading;

 

namespace RadioCs

{

    public partial class MainForm : Form

    {

 

        public MainForm()

        {

            InitializeComponent();

            FormClosed += Form1_FormClosed;

            btnPlay.Click += btnPlay_Click;

            btnStop.Click += btnStop_Click;

        }

 

        private void btnPlay_Click(System.Object sender, System.EventArgs e)

        {

            ReadRadio("http://www.wmph.org:7050/wmph64k");

        }

 

 

        private void btnStop_Click(System.Object sender, System.EventArgs e)

        {

            if ((t != null) && t.ThreadState == ThreadState.Running)

            {

                t.Abort();

                btnStop.Enabled = false;

                btnPlay.Enabled = true;

            }

        }

 

        private PlayerEx plex = new Alvas.Audio.PlayerEx(true);

        private System.Threading.Thread t;

 

        private void ReadRadio(string StreamURL)

        {

            btnStop.Enabled = true;

            btnPlay.Enabled = false;

            t = new Thread(new ParameterizedThreadStart(ThreadProc));

            t.Start(StreamURL);

        }

 

        private void ThreadProc(object StreamURL)

        {

            System.Net.HttpWebRequest WebReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(StreamURL.ToString());

 

            Uri MyURI = new Uri(StreamURL.ToString());

 

            WebReq.Headers.Clear();

            WebReq.Timeout = 5000;

            WebReq.Headers.Add("GET", MyURI.AbsolutePath + " HTTP/1.0");

            WebReq.UserAgent = "WinampMPEG/5.0";

            WebReq.Headers.Add("Icy-MetaData", "1");

            System.Net.WebResponse WebRes = WebReq.GetResponse();

            System.IO.Stream oReader = WebRes.GetResponseStream();

            int MetaInterval = Int32.Parse(WebRes.Headers["icy-metaint"]);

            byte[] data = new byte[MetaInterval];

            byte b = 0;

            Mp3Writer mw = new Mp3Writer(File.Create("out.mp3"));

            int BlockCount = 0;

            try

            {

                while (true)

                {

                    b = (byte)oReader.ReadByte();

                    if (BlockCount == MetaInterval)

                    {

                        //Metadata loop

                        mw.WriteData(data);

                        if (plex.State == DeviceState.Closed)

                        {

                            Mp3Reader mr = new Mp3Reader(new MemoryStream(data));

                            IntPtr format = mr.ReadFormat();

                            mr.Close();

                            plex.OpenPlayer(format);

                            plex.StartPlay();

                        }

                        plex.AddData(data);

                        int MetaDataLength = b * 16;

 

                        if (MetaDataLength > 0)

                        {

                            byte[] MetaArray = new byte[MetaDataLength];

                            oReader.Read(MetaArray, 0, MetaDataLength);

                            System.Text.ASCIIEncoding AEnc = new System.Text.ASCIIEncoding();

 

                            string TempMetaData = AEnc.GetString(MetaArray);

 

                            //Trim it down

                            int StartPosition = TempMetaData.IndexOf("'") + 1;

                            int EndPosition = TempMetaData.IndexOf("';", StartPosition);

                            TempMetaData = TempMetaData.Substring(StartPosition, EndPosition - StartPosition);

                            Console.WriteLine(TempMetaData);

                        }

                        BlockCount = 0;

                        continue;

                    }

                    else

                    {

                        data[BlockCount] = b;

                    }

                    BlockCount = BlockCount + 1;

                }

            }

            finally

            {

                oReader.Close();

                mw.Close();

                plex.ClosePlayer();

            }

        }

 

        private void Form1_FormClosed(System.Object sender, System.Windows.Forms.FormClosedEventArgs e)

        {

            btnStop.PerformClick();

        }

    }

}


Up

69. I try to convert a file on my web page but the process get stuck. The web page seems like it tries to load something but won't go on. What can I do?

Demo version shows the Nag-Screen. Use the Alt+Tab to find it and click "OK" button.

Up

70. I'm trying to trial your software, building it into our web application but the trial version I have downloaded won't work in my web app as it keeps trying to pop up a 'nag screen' which causes the app to throw an error. Is there any way to turn this off?

For test this you need start your web app under built-in VisualStudio web server (or IIS Express) instead of IIS and press NagScreen "OK" button.
Please use Alt+Tab for find NagScreen. This is limitation of the trial version.

Up

71. We are evaluating your Alvas.Audio product for a .net server side mixer and aren't able to evaluate it completely since we keep getting this error: 'Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.' The error seems to come from the Alvas.Audio.AboutBox.ShowNagScreen, which I would guess has to do that we are running a demo. Is there any way of testing server side things without getting that error just to make sure that it works for our project?

What type of applications do you use? For test purpose please
1. use the built-in VisualStudio webserver (or IIS Express) instead of IIS for ASP.Net application.
2. Or use the console application instead of Windows Service.

Up

72. When converting audio from Wav to Mp3 and NOT using the Wave2Mp3 function, do you always need to convert the wave data into PCM data before converting it to MP3? Is there a reason for doing that?

Wave is container format. Please see
http://en.wikipedia.org/wiki/Wav. Wave files can contain audio in various formats (PCM, ADPCM, MP3 and other). PCM(http://en.wikipedia.org/wiki/PCM) is uncompressed format. Other audio formats are compressed.

Before converting data from one compressed format to another they need to be unpacked in PCM (uncompressed format).
Standard scheme of converting data: [CompressedFormat1] -> PCM 16 bit -> [CompressedFormat2].
For example, PCM 8 bit -> PCM 16 bit -> mp3.
Up

73. I have to connect to a SHOUTcast stream, take 5 seconds of the sound then detect if there is silence (no sound above -14db). Would you be so kind to provide us with some sample?

using System;

using System.Windows.Forms;

using System.Net;

using System.IO;

using Alvas.Audio;

 

namespace RadioCs

{

    public partial class frmMain : Form

    {

        public frmMain()

        {

            InitializeComponent();

            t.Interval = 15 * 60 * 1000;

            t.Tick += new EventHandler(t_Tick);

            t.Enabled = true;

        }

 

        Timer t = new Timer();

 

        void t_Tick(object sender, EventArgs e)

        {

            if (CheckSilent("http://www.wmph.org:7050/wmph64k", 10000, -14))

            {

                Console.WriteLine("Alert!");

            }

        }

 

        private static short dB2Short(double dB)

        {

            double times = Math.Pow(10, dB / 10);

            return (short)(short.MaxValue * times);

        }

 

        private bool CheckSilent(string StreamURL, int timeOut, double mindb)

        {

            HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(StreamURL);

 

            Uri MyURI = new Uri(StreamURL);

 

            WebReq.Headers.Clear();

            WebReq.Timeout = timeOut;

            WebReq.Headers.Add("GET", MyURI.AbsolutePath + " HTTP/1.0");

            WebReq.UserAgent = "WinampMPEG/5.0";

            WebReq.Headers.Add("Icy-MetaData", "1");

            WebResponse WebRes = WebReq.GetResponse();

            Stream oReader = WebRes.GetResponseStream();

            int MetaInterval = int.Parse(WebRes.Headers["icy-metaint"]);

            byte[] data = new byte[MetaInterval];

            byte b = 0;

            int BlockCount = 0;

            int pass = 0;

            MemoryStream ms = new MemoryStream();

            try

            {

                while (true)

                {

 

                    b = (byte)oReader.ReadByte();

                    if (BlockCount == MetaInterval)

                    {

                        ms.Write(data, 0, data.Length);

                        pass += 1;

                        if (pass >= 5)

                        {

                            Mp3Reader mr = new Mp3Reader(ms);

                            IntPtr format = mr.ReadFormat();

                            short[] buffer = AudioCompressionManager.RecalculateData(format, ms.ToArray(), -1);

                            mr.Close();

                            int silentLevel = dB2Short(mindb);

                            for (int i = 0; i < buffer.Length; i++)

                            {

                                if (buffer[i] > silentLevel)

                                {

                                    return false;

                                }

                            }

                            return true;

                        }

                        int MetaDataLength = b * 16;

 

                        if (MetaDataLength > 0)//skip metadata

                        {

                            byte[] MetaArray = new byte[MetaDataLength];

                            oReader.Read(MetaArray, 0, MetaDataLength);

                        }

                        BlockCount = 0;

                        continue;

                    }

 

                    else

                    {

                        data[BlockCount] = b;

                    }

 

                    BlockCount = BlockCount + 1;

                }

            }

            finally

            {

                oReader.Close();

            }

        }

 

    }

}


Up

74. I have multiple audio tracks with nothing but music. I have multiple recorded voice tracks no longer than 2-3 seconds each. What I would like to do is 'overlay' a voice track onto an audio track at a specified time and output the results to a single file. E.g. Audio track is 2 minutes long, and I would like to insert the voice track at 23 seconds as well 1m 05 seconds and at 1m 40 seconds. Can Alvas.Audio accomplish this sort of task for me??

Imports System.IO

Imports Alvas.Audio

 

Public Class Form1

 

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

 

        MixMany("c:\audio\files\")

 

    End Sub

 

    Private Shared Sub Debug(ByVal name As String, ByVal wf As WaveFormat)

        Dim format As String = "Variable: [{0}], FormatTag: {1}, Channels: {2}, SamplesPerSec: {3}, BitsPerSample: {4}, BlockAlign: {5}, AvgBytesPerSec: {6}"

        Console.WriteLine(format, name, wf.wFormatTag, wf.nChannels, wf.nSamplesPerSec, wf.wBitsPerSample, wf.nBlockAlign, wf.nAvgBytesPerSec)

    End Sub

 

    Private Shared Sub MixMany(ByVal dir As String)

 

        Dim format1 As IntPtr

        Dim data1 As Byte()

 

        ReadData(dir + "The Friendship Song.mp3", format1, data1)

 

        Dim format2 As IntPtr

        Dim data2 As Byte()

 

        ReadData(dir + "Kailin 1.mp3", format2, data2)

 

        Dim wf1 As WaveFormat = AudioCompressionManager.GetWaveFormat(format1)

        Debug("wf1", wf1)

        Dim wf2 As WaveFormat = AudioCompressionManager.GetWaveFormat(format2)

        Debug("wf1", wf2)

 

        If Not wf1.Equals(wf2) Then

            data2 = AudioCompressionManager.Convert(format2, format1, data2, False)

        End If

 

        Dim data As Byte() = AudioCompressionManager.MixMany(format1, data1, data2, wf1.nSamplesPerSec * 27.1, wf1.nSamplesPerSec * 83.28)

        Dim formatMp3 As IntPtr = AudioCompressionManager.GetCompatibleFormat(format1, AudioCompressionManager.MpegLayer3FormatTag)

        Debug("wfMp3", AudioCompressionManager.GetWaveFormat(formatMp3))

 

        Dim dataMp3 As Byte() = AudioCompressionManager.Convert(format1, formatMp3, data, False)

 

        Dim mw As New Mp3Writer(File.Create(dir + "Test002.mp3"))

        mw.WriteData(dataMp3)

        mw.Close()

 

        MsgBox("Done!")

 

    End Sub

 

    Private Shared Sub ReadData(ByVal fileName As String, ByRef format1 As IntPtr, ByRef data1 As Byte())

        Dim dr1 As New Mp3Reader(File.OpenRead(fileName))

        format1 = dr1.ReadFormat()

        data1 = dr1.ReadData()

        dr1.Close()

        Dim format1Pcm As IntPtr = AudioCompressionManager.GetCompatibleFormat(format1, AudioCompressionManager.PcmFormatTag)

        Dim data1Pcm() As Byte = AudioCompressionManager.Convert(format1, format1Pcm, data1, False)

        format1 = format1Pcm

        data1 = data1Pcm

    End Sub

 

End Class


Up

75. Effectively, I have a block of memory which contains A-law data and I want to play the data using vb.net. Can you provide some sample code on how I can achieve this with PlayerEx?

        Private playEx As PlayerEx = New PlayerEx()

 

        Private Sub Play(ByVal data As Byte())

            Dim wf As WaveFormat = New WaveFormat()

            wf.wFormatTag = AudioCompressionManager.MuLawFormatTag ' or AudioCompressionManager.ALawFormatTag

            wf.nChannels = 1 ' or 2

            wf.nSamplesPerSec = 8000 ' or other

            Dim format As IntPtr = AudioCompressionManager.GetFormatList(wf)(0).FormatHandle

            playEx.OpenPlayer(format)

            playEx.AddData(data)

            playEx.StartPlay()

        End Sub


Up

76. Can I use Alvas.Audio to play(stream) MP3 from the buffer of byte array. Please explain it with sample code in c#.

        private void btnTest_Click(object sender, EventArgs e)

        {

            PlayMp3Array(File.ReadAllBytes("play.mp3"));

        }

 

        PlayerEx plex = new PlayerEx();

 

        private void PlayMp3Array(byte[] data)

        {

            MemoryStream ms = new MemoryStream(data);

            Mp3Reader mr = new Mp3Reader(ms);

            plex.OpenPlayer(mr.ReadFormat());

            plex.AddData(mr.ReadData());

            mr.Close();

            plex.StartPlay();

        }


Up

77. Is possible to mix to mix two audio file, using an offset to start playing one of them (for example, the first start playing and second plays after one second).

        private void btnTest_Click(object sender, EventArgs e)

        {

            string path = @"D:\audio\files\";

            Mix(path + "out.wav", path + "PLUTO.wav", path + "MS702.wav", 1);

        }

 

        private void Mix(string outfile, string infile1, string infile2, int shiftSec)

        {

            WaveReader wr1 = new WaveReader(File.OpenRead(infile1));

            WaveReader wr2 = new WaveReader(File.OpenRead(infile2));

            IntPtr format1 = wr1.ReadFormat();

            WaveFormat wf = AudioCompressionManager.GetWaveFormat(format1);

            WaveWriter ww = new WaveWriter(File.Create(outfile), AudioCompressionManager.FormatBytes(format1));

            byte[] data0 = wr1.ReadData(0, shiftSec);

            byte[] data1 = wr1.ReadData(shiftSec);

            byte[] data2 = wr2.ReadData();

            byte[] mixData = AudioCompressionManager.Mix(format1, data2, data1);

            ww.WriteData(data0);

            ww.WriteData(mixData);

            ww.Close();

            wr2.Close();

            wr1.Close();

        }


Up

78. Have you added some support for simple audio efects like simple echo, reverb or distorsion or something like that.

Yes. Please see how to use Chorus, Compressor, Distortion, Echo, Flanger, Gargle, I3DL2Reverb, ParamEq, WavesReverb audio effects in EffectsCs and EffectsVb examples.

Up

79. How can I remove the first .5 of a second from mp3 file? I can get it to do a whole second, but I just need to remove the first half.

        private void Skip05sec()

        {

            Mp3Reader mr = new Mp3Reader(File.OpenRead("in.mp3"));

            IntPtr format = mr.ReadFormat();

            byte[] data = mr.ReadDataInBytes(AudioCompressionManager.Milliseconds2Bytes(format, 500));

            mr.Close();

            Mp3Writer mw = new Mp3Writer(File.Create("out.mp3"));

            mw.WriteData(data);

            mw.Close();

        }


Up

80. Is it possible to get the bit rate of an mp3? (I can see how to get sample rate, and bits per sample but not bit rate).

            Mp3Reader mr = new Mp3Reader(File.OpenRead("in.mp3"));

            IntPtr format = mr.ReadFormat();

            WaveFormat wf = AudioCompressionManager.GetWaveFormat(format);

            int bitsPerSecond = wf.nAvgBytesPerSec * 8;

            mr.Close();


Up

81. Can you player easily play looping sounds (like the My.Computer.Audio.Play(file,AudioPlayMode.BackgroundLoop)? A small VB.NET example would be appreciated.

Imports Alvas.Audio

Imports System.IO

 

Public Class MainForm

 

    Private plex As New PlayerEx()

    Private data As Byte() = Nothing

 

    Private Sub Init()

        Dim wr As New WaveReader(File.OpenRead("in.wav"))

        Dim format As IntPtr = wr.ReadFormat()

        data = wr.ReadData()

        wr.Close()

        AddHandler plex.Done, AddressOf plex_Done

        plex.OpenPlayer(format)

        plex.StartPlay()

        plex.AddData(data)

    End Sub

 

    Private Sub plex_Done(ByVal sender As Object, ByVal e As DoneEventArgs)

        If e.IsEndPlaying Then

            plex.AddData(data)

        End If

 

 

    End Sub

 

 

    Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTest.Click

        Init()

    End Sub

 

 

End Class


Up

82. Is it posiable to play from one file selected parts as if they were one seqwence with no pausing betwen. E.g play from the 10 sec for 5 sec and imidiatly from position 20 sec for 7 sec long?

        static void PlayPositions(string fileName)

        {

            WaveReader wr = new WaveReader(File.OpenRead(fileName));

            IntPtr format = wr.ReadFormat();

            byte[] data1 = wr.ReadData(10, 5);

            byte[] data2 = wr.ReadData(20, 7);

            wr.Close();

            PlayerEx plex = new PlayerEx();

            plex.OpenPlayer(format);

            plex.StartPlay();

            plex.AddData(data1);

            plex.AddData(data2);

        }


Up

83. I need to do audio recording on my web application ASP.Net. Can I use Alvas.Audio for these purposes?

For audio recording and playback in a Web application need to use client technologies such as Silverlight or Flash. Alvas.Audio can be used on the server side, for example, to convert from one audio format to another, editing, and so forth.

Up

84. Combine an AIF file with 2 seconds of silence with another AIF file, and write that out as a mono 112kbps MP3. Is it possible to provide me with a sample of how to do this?

        private static void AiffToMp3()

        {

            const int samplerate = 44100;

            string path = @"d:\Work\";

            string file1 = "one.aif";

            IntPtr format1;

            WaveFormat wf1;

            byte[] data1;

            GetAudioData(path + file1, out format1, out wf1, out data1);

            //ResamplePcm(ref format1, ref wf1, ref data1, samplerate);

            string file2 = "two.aif";

            IntPtr format2;

            WaveFormat wf2;

            byte[] data2;

            GetAudioData(path + file2, out format2, out wf2, out data2);

            //ResamplePcm(ref format2, ref wf2, ref data2, samplerate);

            if (wf1.Equals(wf2))

            {

                IntPtr formatMp3 = IntPtr.Zero;

                FormatDetails[] fdArr = AudioCompressionManager.GetCompatibleFormatList(format1);

                foreach (FormatDetails fd in fdArr)

                {

                    WaveFormat wf = AudioCompressionManager.GetWaveFormat(fd.FormatHandle);

                    if (wf.wFormatTag == AudioCompressionManager.MpegLayer3FormatTag && wf.nAvgBytesPerSec * 8 == 112000)

                    {

                        formatMp3 = fd.FormatHandle;

                        break;

                    }

                }

                if (formatMp3 != IntPtr.Zero)

                {

                    byte[] silence = AudioCompressionManager.Silence(format1, 2000);//2 seconds

                    AcmConverter acm = new AcmConverter(format1, formatMp3, false);

                    byte[] data1Mp3 = acm.Convert(data1);

                    byte[] silenceMp3 = acm.Convert(silence);

                    byte[] data2Mp3 = acm.Convert(data2);

                    acm.Close();

                    string fileMp3 = "out.mp3";

                    Mp3Writer mw = new Mp3Writer(File.Create(path + fileMp3));

                    mw.WriteData(data1Mp3);

                    mw.WriteData(silenceMp3);

                    mw.WriteData(data2Mp3);

                    mw.Close();

                }

            }

            else

            {

                MessageBox.Show("Audio formats should be identical. Require additional conversion of audio data to a single format.");

            }

        }

 

        private static void GetAudioData(string fileName, out IntPtr format, out WaveFormat wf, out byte[] data)

        {

            DsReader dr1 = new DsReader(fileName);

            format = dr1.ReadFormat();

            wf = AudioCompressionManager.GetWaveFormat(format);

            data = dr1.ReadData();

            dr1.Close();

        }


Up

85. I need the MP3 to be of 44.1khz sample rate. The source AIFF files are at 48k. I attempted to specify the mp3 format with 44.1khz, but then the AcmConverter constructor throws an exception 'It is not succeeded to open the stream of conversion of data' How can I perform a sample rate conversion as well?

You need first to resample your audio data from 48khz to 44.1khz. Uncomment the calls of ResamplePcm method in the previous tip, and add the code below

        private static void ResamplePcm(ref IntPtr format, ref WaveFormat wf, ref byte[] data, int sampleRate)

        {

            if (wf.wFormatTag == AudioCompressionManager.PcmFormatTag)

            {

                IntPtr formatPcm = AudioCompressionManager.GetPcmFormat(wf.nChannels, wf.wBitsPerSample, sampleRate);

                byte[] dataPcm = AudioCompressionManager.Resample(format, data, formatPcm);

                wf = AudioCompressionManager.GetWaveFormat(formatPcm);

                format = formatPcm;

                data = dataPcm;

            }

            else

            {

                MessageBox.Show("First you need to decode audio data to PCM");

            }

        }


Up

86. Is it possible to create 100 milliseconds of 1k sine wave (at-1db) with this library?

        private void TestSine()

        {

            IntPtr format;

            byte[] data;

            GetSineWave(1000, 100, 44100, -1, out format, out data);

            WaveWriter ww = new WaveWriter(File.Create(@"d:\work\sine.wav"),

                AudioCompressionManager.FormatBytes(format));

            ww.WriteData(data);

            ww.Close();

        }

 

        private void GetSineWave(double freq, int durationMs, int sampleRate, short decibel, out IntPtr format, out byte[] data)

        {

            short max = dB2Short(decibel);//short.MaxValue

            double fs = sampleRate; // sample freq

            int len = sampleRate * durationMs / 1000;

            short[] data16Bit = new short[len];

            for (int i = 0; i < len; i++)

            {

                double t = (double)i / fs; // current time

                data16Bit[i] = (short)(Math.Sin(2 * Math.PI * t * freq) * max);

            }

            IntPtr format1 = AudioCompressionManager.GetPcmFormat(1, 16, (int)fs);

            byte[] data1 = new byte[data16Bit.Length * 2];

            Buffer.BlockCopy(data16Bit, 0, data1, 0, data1.Length);

            format = format1;

            data = data1;

        }

 

        private static short dB2Short(double dB)

        {

            double times = Math.Pow(10, dB / 10);

            return (short)(short.MaxValue * times);

        }


Up

87. I need a simple way to record audio and store it into a file. I'm not concerned with its format but rather with simplicity. I'm just trying to get a handle of it and would like to know if it is possible to have an example (as simple as possible) on how I can click a button to start recording and button to stop recording and save the recording to a file. can you help?

for VB.Net

Imports System

Imports System.Windows.Forms

Imports Alvas.Audio

Imports System.IO

 

Namespace SimpleRecorder

    Partial Public Class FormMain

        Inherits Form

        Public Sub New()

            InitializeComponent()

            Init()

        End Sub

 

        Private rp As RecordPlayer

 

        Private Sub Init()

            rp = New RecordPlayer()

            rp.RecorderID = -1

        End Sub

 

        Private Sub btnRecord_Click(ByVal sender As Object, ByVal e As EventArgs)

            If rp.State <> DeviceState.Closed Then

                rp.Close()

            End If

            Dim format As IntPtr = AudioCompressionManager.GetPcmFormat(1, 16, 44100)

            rp.Open(New WaveReadWriter(File.Create("rec.wav"), AudioCompressionManager.FormatBytes(format)))

            rp.Record()

        End Sub

 

        Private Sub btnStop_Click(ByVal sender As Object, ByVal e As EventArgs)

            rp.[Stop]()

        End Sub

    End Class

End Namespace

For c#

using System;

using System.Windows.Forms;

using Alvas.Audio;

using System.IO;

 

namespace SimpleRecorder

{

    public partial class FormMain : Form

    {

        public FormMain()

        {

            InitializeComponent();

            Init();

        }

 

        RecordPlayer rp;

 

        private void Init()

        {

            rp = new RecordPlayer();

            rp.RecorderID = -1;

        }

 

        private void btnRecord_Click(object sender, EventArgs e)

        {

            if (rp.State != DeviceState.Closed)

            {

                rp.Close();

            }

            IntPtr format = AudioCompressionManager.GetPcmFormat(1, 16, 44100);

            rp.Open(new WaveReadWriter(File.Create("rec.wav"), AudioCompressionManager.FormatBytes(format)));

            rp.Record();

        }

 

        private void btnStop_Click(object sender, EventArgs e)

        {

            rp.Stop();

        }

    }

}


Up

88. I have 10 wav files with the same format - CCITT u-Law, 8000 Hz, mono. How to merge them together using Alvas.Audio?

        private void JoinWav()

        {

            string[] files = new string[] { "1990764-ENG-CONSEC-RESPONSE7.WAV","1990764-ND_A.WAV", "1990764-SIGHT-SP.WAV",

                "1990764-SP-CONSEC-RESPONSE6.WAV","1990764-VOCABWORD-004-12-SP.WAV","bi-consec-1-successful.wav",

                "bi-transition-instruct.wav","nd_B.wav","sightreceived_B.wav","teststamp_A.wav" };

            AudioCompressionManager.Join("res.wav", files);

        }


Up

89. Has Alvas.Audio got the ability to convert from a WAV to the various MP3 bit rates (128,160,192,etc.)?

            int bitRate = 128000;//128000,160000,192000

            ToMp3("in.wav", bitRate);

 

        private static void ToMp3(string waveFile, int bitRate)

        {

            WaveReader wr = new WaveReader(File.OpenRead(waveFile));

            IntPtr format = wr.ReadFormat();

            byte[] data = wr.ReadData();

            wr.Close();

            FormatDetails[] fdArray = AudioCompressionManager.GetCompatibleFormatList(format, true);

            foreach (FormatDetails fd in fdArray)

            {

                if (fd.FormatTag == AudioCompressionManager.MpegLayer3FormatTag)

                {

                    WaveFormat wf = AudioCompressionManager.GetWaveFormat(fd.FormatHandle);

                    if (wf.nAvgBytesPerSec * 8 == bitRate)

                    {

                        byte[] dataMp3 = AudioCompressionManager.Convert(format, fd.FormatHandle, data, false);

                        Mp3Writer mw = new Mp3Writer(File.Create(waveFile + ".mp3"));

                        mw.WriteData(dataMp3);

                        mw.Close();

                        break;

                    }

                }

            }

        }


Up

90. The application of our software is to capture speech and segment the audio files during natural pauses in speech. So, what I need to do is when someone stops speaking for say, 5 seconds, we would detect that, stop writing data, close the file, open a new one, and wait for sound to start back up before recording again.

using System;

using System.Collections.Generic;

using System.Windows.Forms;

using Alvas.Audio;

using System.IO;

 

namespace SilentRecorder

{

    public partial class MainForm : Form

    {

        public MainForm()

        {

            InitializeComponent();

            Init();

        }

 

        private void Init()

        {

            rex.BufferSizeInMS = 100;

            rex.Format = AudioCompressionManager.GetPcmFormat(1, 16, 441000);

            rex.Data += new RecorderEx.DataEventHandler(rex_Data);

            rex.Close += new EventHandler(rex_Close);

        }

 

        void rex_Close(object sender, EventArgs e)

        {

            WriteFile();

        }

 

        void rex_Data(object sender, DataEventArgs e)

        {

            queue.Enqueue(e.Data);

            bool isSilent = AudioCompressionManager.CheckSilent(rex.Format, e.Data, 12000);

            if (isSilent)

            {

                x += 1;

                if (x >= 50)//50 * 100 ms = 5 sec

                {

                    WriteFile();

                }

            }

            else

            {

                x = 0;

            }

        }

 

        private void WriteFile()

        {

            int queueCount = queue.Count;

            if (queueCount <= x)

            {

                queue.Clear();

            }

            else

            {

                WaveWriter ww = new WaveWriter(File.Create(string.Format("{0}.wav", Guid.NewGuid())),

                    AudioCompressionManager.FormatBytes(rex.Format));

                for (int i = 0; i < queueCount + 10 - x; i++)

                {

                    if (queue.Count > 0)

                    {

                        byte[] data = queue.Dequeue();

                        ww.WriteData(data);

                    }

                }

                ww.Close();

                queue.Clear();

            }

            x = 0;

        }

 

        int x = 0;

        Queue<byte[]> queue = new Queue<byte[]>();

        RecorderEx rex = new RecorderEx();

 

        private void btnRecord_Click(object sender, EventArgs e)

        {

            rex.StartRecord();

        }

 

        private void btnStop_Click(object sender, EventArgs e)

        {

            rex.StopRecord();

        }

    }

}


Up

91. Is it possible for converting any audio file format to wave audio file with 8kBit/sec compression?

        static void AnyToWav(string fileName)

        {

            DsReader dr = new DsReader(fileName);

            IntPtr formatPcm = dr.ReadFormat();

            byte[] dataPcm = dr.ReadData();

            dr.Close();

 

            IntPtr formatMp3 = AudioCompressionManager.GetMp3Format(1, 8, 8000);//8kBit/sec

            IntPtr formatPcmCompatible = AudioCompressionManager.GetCompatibleFormat(formatMp3, AudioCompressionManager.PcmFormatTag);

 

            byte[] dataPcmCompatible = AudioCompressionManager.Convert(formatPcm, formatPcmCompatible, dataPcm, false);

 

            byte[] dataMp3 = AudioCompressionManager.Convert(formatPcmCompatible, formatMp3, dataPcmCompatible, false);

 

            WaveWriter ww = new WaveWriter(File.Create(fileName + ".wav"), AudioCompressionManager.FormatBytes(formatMp3));

            ww.WriteData(dataMp3);

            ww.Close();

        }


Up

92. I'm working with a couple different source formats now: * a ULAW encoded VOX file at 8 bits-per-sample, 8Khz, mono; * a PCM WAV file at 16 bits-per-sample, 8Khz, mono. Both need to end up as MP3 ... preferred format is 32kbps mono (24Khz).

* for ULAW encoded VOX file at 8 bits-per-sample, 8Khz, mono

    Private Shared Sub ULAW2Mp3(ByVal fileName As String)

        Dim wf As New WaveFormat()

        wf.wFormatTag = AudioCompressionManager.MuLawFormatTag

        wf.wBitsPerSample = 8

        wf.nSamplesPerSec = 8000

        wf.nChannels = 1

        Dim format As IntPtr = AudioCompressionManager.GetFormatList(wf)(0).FormatHandle

        Dim rr As New RawReader(File.OpenRead(fileName), format)

        Dim data As Byte() = rr.ReadData()

        rr.Close()

        Dim formatPcm16bit As IntPtr = IntPtr.Zero

        Dim dataPcm16bit As Byte() = Nothing

        AudioCompressionManager.ToPcm16Bit(format, data, formatPcm16bit, dataPcm16bit)

        Dim formatMp3 As IntPtr = AudioCompressionManager.GetMp3Format(1, 32, 24000)

 

        Dim formatPcmCompatible As IntPtr = AudioCompressionManager.GetCompatibleFormat(formatMp3, AudioCompressionManager.PcmFormatTag)

        Dim dataPcmCompatible As Byte() = AudioCompressionManager.Convert(formatPcm16bit, formatPcmCompatible, dataPcm16bit, False)

 

        Dim dataMp3 As Byte() = AudioCompressionManager.Convert(formatPcmCompatible, formatMp3, dataPcmCompatible, False)

        Dim mw As New Mp3Writer(File.Create(fileName & ".mp3"))

        mw.WriteData(dataMp3)

        mw.Close()

    End Sub

* for PCM WAV file at 16 bits-per-sample, 8Khz, mono

    Private Shared Sub Wav2Mp3(ByVal fileName As String)

        Dim wavR As WaveReader = New WaveReader(File.OpenRead(fileName))

        Dim ptrWavFormat As IntPtr = wavR.ReadFormat()

        Dim bytWavData As Byte() = wavR.ReadData()

        Dim intDuration As Integer = wavR.GetDurationInMS()

        wavR.Close()

 

        Dim ptrPcm16Format As IntPtr = IntPtr.Zero

        Dim bytPcm16Data As Byte() = Nothing

        AudioCompressionManager.ToPcm16Bit(ptrWavFormat, bytWavData, ptrPcm16Format, bytPcm16Data)

 

        Dim ptrMp3Format As IntPtr = AudioCompressionManager.GetMp3Format(channels:=1S, kbps:=32S, samplesPerSec:=24000)

 

        Dim ptrPcmCompatibleFormat As IntPtr = AudioCompressionManager.GetCompatibleFormat(ptrMp3Format, AudioCompressionManager.PcmFormatTag)

 

        Dim bytPcmCompatibleData As Byte() = AudioCompressionManager.Convert(oldFormat:=ptrPcm16Format, newFormat:=ptrPcmCompatibleFormat, data:=bytPcm16Data, fastConversion:=False)

 

        Dim bytMp3Data As Byte() = AudioCompressionManager.Convert(oldFormat:=ptrPcmCompatibleFormat, newFormat:=ptrMp3Format, data:=bytPcmCompatibleData, fastConversion:=False)

    End Sub


Up

93. Is it possible for converting any audio file to mp3?

        static void AnyToMp3(string fileName)

        {

            DsReader dr = new DsReader(fileName);

            IntPtr formatPcm = dr.ReadFormat();

            byte[] dataPcm = dr.ReadData();

            dr.Close();

            IntPtr formatMp3 = AudioCompressionManager.GetCompatibleFormat(formatPcm,

                AudioCompressionManager.MpegLayer3FormatTag);

            byte[] dataMp3 = AudioCompressionManager.Convert(formatPcm, formatMp3, dataPcm, false);

            Mp3Writer mw = new Mp3Writer(File.Create(fileName + ".mp3"));

            mw.WriteData(dataMp3);

            mw.Close();

        }


Up

94. How to convert a large Wave file to Mp3?

        private static void BigWav2Mp3(string wavFile)

        {

            using (WaveReader wr = new WaveReader(File.OpenRead(wavFile)))

            {

                IntPtr format = wr.ReadFormat();

                IntPtr formatMp3 = AudioCompressionManager.GetCompatibleFormat(format, AudioCompressionManager.MpegLayer3FormatTag);

                AcmConverter acm = new AcmConverter(format, formatMp3, false);

                const int seconds = 60;

                using (Mp3Writer mw = new Mp3Writer(File.Create(wavFile + ".mp3")))

                {

                    int i = 0;

                    while (true)

                    {

                        byte[] data = wr.ReadData(i * seconds, seconds);

                        if (data == null || data.Length == 0)

                        {

                            break;

                        }

                        byte[] dataMp3 = acm.Convert(data);

                        mw.WriteData(dataMp3);

                        i += 1;

                    }

                }

                acm.Close();

            }

        }


Up

95. Can we draw Alvas.Audio object on C# form like other tools in .net?

If you want to see components in Visual Studio Toolbox - Right-click on Toolbox, click Customize Toolbox and choose visual components from Alvas.Audio.dll

Up

96. I have a few ten wav files and want to amplify all of them (automatically) so that they can be played louder. The code must detect the file's current maximum sound level and then automatically bring them to maximum before clipping (optional, it can boost a few dB more beyond the Maximum level for clipping as assigned by user).

        private void Normalize(string fileName)

        {

            WaveReader wr = new WaveReader(File.OpenRead(fileName));

            IntPtr format = wr.ReadFormat();

            WaveWriter ww = new WaveWriter(File.Create(fileName + ".wav"), AudioCompressionManager.FormatBytes(format));

            AudioCompressionManager.Normalize(wr, ww);

            ww.Close();

            wr.Close();

        }


Up

97. Is It possible to use headerless .vox audio file with 'G.711 Alaw' format for converting to mp3 in vb.net?

For example
Format: G.711 Alaw
Sample rate: 8000
Channel: Mono

    Private Shared Sub Alaw2Mp3(ByVal fileName As String)

        Dim wf As New WaveFormat()

        wf.wFormatTag = AudioCompressionManager.ALawFormatTag

        wf.nSamplesPerSec = 8000

        wf.nChannels = 1

        Dim formatList As FormatDetails() = AudioCompressionManager.GetFormatList(wf)

        Dim format As IntPtr = formatList(0).FormatHandle

        Dim rr As New RawReader(File.OpenRead(fileName), format)

        Dim data As Byte() = rr.ReadData()

        rr.Close()

        Dim formatPcm16bit As IntPtr = IntPtr.Zero

        Dim dataPcm16bit As Byte() = Nothing

        AudioCompressionManager.ToPcm16Bit(format, data, formatPcm16bit, dataPcm16bit)

        Dim formatMp3 As IntPtr = AudioCompressionManager.GetCompatibleFormat(formatPcm16bit, AudioCompressionManager.MpegLayer3FormatTag)

 

        Dim dataMp3 As Byte() = AudioCompressionManager.Convert(formatPcm16bit, formatMp3, dataPcm16bit, False)

        Dim mw As New Mp3Writer(File.Create(fileName & ".mp3"))

        mw.WriteData(dataMp3)

        mw.Close()

    End Sub


Up

98. I need to extract the audio data from a FLV with C#

        private static void Flv2Wav()

        {

            string fileName = @"c:\ALVAS\trailer_2288.flv";

            DsReader dr = new DsReader(fileName);

            if (dr.HasAudio)

            {

                IntPtr format = dr.ReadFormat();

                byte[] data = dr.ReadData();

                WaveWriter ww = new WaveWriter(File.Create(fileName + ".wav"),

                    AudioCompressionManager.FormatBytes(format));

                ww.WriteData(data);

                ww.Close();

            }

            dr.Close();

        }


Up

99. I have an a-law mono 8000 Hz wav which I am trying to convert into mp3… I am getting a pretty bad echo and wondered if there was a better way to convert? Perhaps this could be a problem with the bitrate of the mp3 being low (8K)? I didn’t see a way to make the MP3 encoder use a higher bitrate than the primary bitrate.

        static void ToMp3(string wavFile, string mp3File)

        {

            WaveReader wr = new WaveReader(File.OpenRead(wavFile));

            IntPtr format = wr.ReadFormat();

            byte[] data = wr.ReadData();

            wr.Close();

            IntPtr formatPcm16bit = IntPtr.Zero;

            byte[] dataPcm16bit = null;

            AudioCompressionManager.ToPcm16Bit(format, data, ref formatPcm16bit, ref dataPcm16bit);

            Resample(ref formatPcm16bit, ref dataPcm16bit);

            IntPtr formatMp3 = AudioCompressionManager.GetCompatibleFormat(formatPcm16bit, AudioCompressionManager.MpegLayer3FormatTag);

            byte[] dataMp3 = AudioCompressionManager.Convert(formatPcm16bit, formatMp3, dataPcm16bit, false);

            Mp3Writer mw = new Mp3Writer(File.Create(mp3File));

            mw.WriteData(dataMp3);

            mw.Close();

        }

 

        static void Resample(ref IntPtr formatPcm16bit, ref byte[] dataPcm16bit)

        {

            WaveFormat wf = AudioCompressionManager.GetWaveFormat(formatPcm16bit);

            IntPtr outFormat = AudioCompressionManager.GetPcmFormat(wf.nChannels, wf.wBitsPerSample, wf.nSamplesPerSec * 2);

            byte[] outData = AudioCompressionManager.Resample(formatPcm16bit, dataPcm16bit, outFormat);

            formatPcm16bit = outFormat;

            dataPcm16bit = outData;

        }


Up

100. I want to change an audio file format into another. Specifically, I want to convert any audio file into 6khz, 16 bit, mono, PCM wav format.

        private static void ToFormat(string fileName)
        {
            //6khz, 16 bit, mono, PCM
            IntPtr pcmFormat = AudioCompressionManager.GetPcmFormat(1, 16, 6000);
            IAudioReader ar = new DsReader(fileName);
            byte[] pcmData = AudioCompressionManager.ToFormat(ar, pcmFormat);
            ar.Close();
            WaveWriter ww = new WaveWriter(File.Create(fileName + ".wav"),
                AudioCompressionManager.FormatBytes(pcmFormat));
            ww.WriteData(pcmData);
            ww.Close();
        }

Up

101. I have a 10 second sound effect wave file. What I would like to do is take that file and repeat it n number of times and then save the longer WAV file to disk.

        private static void RepeatWAV(string fileName, int count)
        {
            WaveReader wr = new WaveReader(File.OpenRead(fileName));
            IntPtr format = wr.ReadFormat();
            byte[] data = wr.ReadData();
            wr.Close();
            WaveWriter ww = new WaveWriter(File.Create(fileName),
                AudioCompressionManager.FormatBytes(format));
            for (int i = 0; i < count; i++)
            {
                ww.WriteData(data);
            }
            ww.Close();
        }

Up

102. I want to play audio(wave) channels(R or L) separate.

        enum Channel
        {
            Left,
            Right,
            Both,
        }

        private void PlayChannel(string fileName, Channel channel)
        {
            DsReader dr = new DsReader(fileName);
            IntPtr format = dr.ReadFormat();
            byte[] data = dr.ReadData();
            dr.Close();
            IntPtr formatMono = IntPtr.Zero;
            byte[] leftData = null;
            byte[] rightData = null;
            AudioCompressionManager.SplitStereo(format, data, ref formatMono, ref leftData, ref rightData);
            PlayerEx plex = new PlayerEx();
            switch (channel)
            {
                case Channel.Left:
                    plex.OpenPlayer(formatMono);
                    plex.AddData(leftData);
                    break;
                case Channel.Right:
                    plex.OpenPlayer(formatMono);
                    plex.AddData(rightData);
                    break;
                case Channel.Both:
                    plex.OpenPlayer(format);
                    plex.AddData(data);
                    break;
            }
            plex.StartPlay();
        }

Up

103. I want to calculate the playing time of the file (ex: 00:05:32).

            using (Mp3Reader mr = new Mp3Reader(File.OpenRead("len.mp3")))
            {
                int durationMS = mr.GetDurationInMS();
                TimeSpan durationTS = TimeSpan.FromMilliseconds(durationMS);
            }

Up

104. How to create a wave STREAM out of raw audio samples in C#?

    byte[] data;// = ...
    IntPtr format = AudioCompressionManager.GetPcmFormat(channels, bitPerSample, samplePerSecond);
    WaveWriter ww = new WaveWriter(new MemoryStream(), AudioCompressionManager.FormatBytes(format));
    ww.WriteData(data);

Up

105. How to programatically change the playback device in C#?

    playEx.PlayerID = 0;//select your sound card
    string fileName = @"c:\test.mp3";
    Mp3Reader br = new Mp3Reader(File.OpenRead(fileName));
    IntPtr format = br.ReadFormat();
    byte[] data = br.ReadData();
    br.Close();
    playEx.OpenPlayer(format);
    playEx.AddData(data);
    playEx.StartPlay();

Up

106. I want to detect the current volume for the default audio recording device of the current computer

private static int RecorderVolume()
{
    RecordPlayer rp = new RecordPlayer();
    rp.RecorderID = -1;
    int recorderVolume = rp.RecorderVolume;
    return recorderVolume;
}

Up

107. How to convert AMR sound stream to PCM uncompressed stream in .NET

    DsReader dr = new DsReader("sample.amr");
    IntPtr formatPcm = dr.ReadFormat();
    byte[] dataPcm = dr.ReadData();
    dr.Close();

Up

108. How to play mp3 files in C#?

    RecordPlayer rp = new RecordPlayer();
    rp.PlayerID = -1;
    rp.Open(new Mp3Reader(File.OpenRead("song.mp3")));
    rp.Play();

Up

109. What is the easiest way to convert a compressed wav file to an uncompressed wav file in C#?

private void ToPcm(string fileName)
{
    IAudioReader wr = new WaveReader(File.OpenRead(fileName));
    IntPtr format = wr.ReadFormat();
    IntPtr formatPcm = AudioCompressionManager.GetCompatibleFormat(format, 
        AudioCompressionManager.PcmFormatTag);
    WaveWriter ww = new WaveWriter(File.Create(fileName + ".wav"), 
        AudioCompressionManager.FormatBytes(formatPcm));
    AudioCompressionManager.Convert(wr, ww, false);
    wr.Close();
    ww.Close();
}

Up

110. I want to change an audio file format into another. Specifically, I want to convert any audio file into 6khz, 16 bit, mono, PCM wav format.

private static void ToFormat(string fileName)
{
    //6khz, 16 bit, mono, PCM
    IntPtr pcmFormat = AudioCompressionManager.GetPcmFormat(1, 16, 6000);
    IAudioReader ar = new DsReader(fileName);
    byte[] pcmData = AudioCompressionManager.ToFormat(ar, pcmFormat);
    ar.Close();
    WaveWriter ww = new WaveWriter(File.Create(fileName + ".wav"),
        AudioCompressionManager.FormatBytes(pcmFormat));
    ww.WriteData(pcmData);
    ww.Close();
}

Up

111. What is the best way to convert various audio formats to PCM? For example: mp3, wav, ogg, vox.

For vox
    using (BinaryReader br = new BinaryReader(File.OpenRead("sample.vox")))
    {
        IntPtr format = AudioCompressionManager.GetPcmFormat(1, 16, 8000);
        using (WaveWriter ww = new WaveWriter(new MemoryStream(), 
            AudioCompressionManager.FormatBytes(format)))
        {
            Vox.Vox2Wav(br, ww);
        }
    }
for other
    DsReader dr = new DsReader("sample.ogg");
    IntPtr formatPcm = dr.ReadFormat();
    byte[] dataPcm = dr.ReadData();
    dr.Close();

Up

112. I have a stream of u-Law compressed PCM data I am extracting from a Camera, I need to play this out the speakers?

private static void Play()
{
    Stream stream = new MemoryStream();//your audio data
    WaveFormat wf = new WaveFormat();
    wf.wFormatTag = AudioCompressionManager.MuLawFormatTag;
    wf.nChannels = 1;//mono or stereo
    wf.nSamplesPerSec = 44100;//sample rate
    FormatDetails[] formatList = AudioCompressionManager.GetFormatList(wf);
    IntPtr format = formatList[0].FormatHandle;//your audio format
    RecordPlayer rp = new RecordPlayer();
    rp.PlayerID = -1;
    rp.Open(new RawReader(stream, format));
    rp.Play();
}

Up

113. I need to mix two audio files. Audio 1 will be a static file and used to 'tag' Audio 2. To be clear I'm talking about an audio tag not an ID3 tag. 1) How can I repeat Audio 1 when mixed with Audio 2 so that the result is the same length as Audio 2? 2) Audio 2 will be an MP3 and I don't want to re-encode it and possibly reduce it's quality.

private static void MixMany(string fileName1, string fileName2)
{
    DsReader dr1 = new DsReader(fileName1);
    byte[] data1 = dr1.ReadData();
    dr1.Close();
    DsReader dr2 = new DsReader(fileName2);
    IntPtr format2 = dr2.ReadFormat();
    byte[] data2 = dr2.ReadData();
    dr2.Close();
    List offsets = new List();
    int x = 0;
    while (x < data2.Length)
    {
        offsets.Add(x);
        x += data1.Length;
    }
    byte[] dataMix = AudioCompressionManager.MixMany(format2, data2, data1, offsets.ToArray());
    IntPtr formatMp3 = AudioCompressionManager.GetCompatibleFormat(format2,
        AudioCompressionManager.MpegLayer3FormatTag);
    byte[] dataMp3 = AudioCompressionManager.Convert(format2, formatMp3, dataMix, false);
    Mp3Writer mw = new Mp3Writer(File.Create(fileName2 + ".mp3"));
    mw.WriteData(dataMp3);
    mw.Close();
}

Up

114. I need convert wma to mp3. It seems to be choking on larger wma's (20mb) or so. It throws an out of memory exception in the DsReader.ReadData function and size of the converted mp3 is twice that of the wma file. What parameter do I use to reduce the size?

        private static void BigToMp3(string fileName)
        {
            DsReader dr = new DsReader(fileName);
            int size = dr.Milliseconds2Bytes(1000000);
            int len = dr.GetLengthInBytes();
            IntPtr format = dr.ReadFormat();
            WaveFormat waveFormat = AudioCompressionManager.GetWaveFormat(format);
            IntPtr formatMp3 = IntPtr.Zero;
            //AudioCompressionManager.GetCompatibleFormat(format, AudioCompressionManager.MpegLayer3FormatTag);
            FormatDetails[] formatList = AudioCompressionManager.GetCompatibleFormatList(format);
            foreach (FormatDetails fd in formatList)
            {
                WaveFormat wf = AudioCompressionManager.GetWaveFormat(fd.FormatHandle);
                //You can experiment with these settings to reduce the size or increase sound quality
                if (wf.wFormatTag == AudioCompressionManager.MpegLayer3FormatTag & wf.nChannels == 1 & 
                    wf.nSamplesPerSec == waveFormat.nSamplesPerSec)
                {
                    formatMp3 = fd.FormatHandle;
                    break;
                }
            }
            AcmConverter ac = new AcmConverter(format, formatMp3, false);
            Mp3Writer ww = new Mp3Writer(File.Create(fileName + ".mp3"));
            int y = 0;
            while (y < len)
            {
                byte[] data = dr.ReadDataInBytes(y, size);
                y += data.Length;
                byte[] newData = ac.Convert(data);
                ww.WriteData(newData);
            }
            ww.Close();
            dr.Close();
        }

Up

115. How to programmatically mute the Windows XP Volume using C#?

PlayerEx.SetVolume(0, 0); or use mixer
void SetPlayerMute(int playerMixerNo, bool value)
{
        Mixer mx = new Mixer();
        mx.MixerNo = playerMixerNo;
        DestinationLine dl = mx.GetDestination(Mixer.Playback);
        if (dl != null)
            foreach (MixerControl ctrl in dl.Controls)
                if (ctrl is MixerMuteControl)
                {
                    ((MixerMuteControl)ctrl).Value = (value) ? 1 : 0;
                    break;
                }
}

Up

116. Is there a way to set the microphone volume in C# (normally done in control panel -> audio -> advanced, go to recording, and then dragging the slider)?

private static void SetRecorderVolumeMax(int recorderMixerNo)
{
    Mixer mx = new Mixer();
    mx.MixerNo = recorderMixerNo;
    DestinationLine dl = mx.GetDestination(Mixer.Recording);
    if (dl != null)
    {
        foreach (MixerControl mc in dl.Controls)
        {
            if (mc is MixerIntControl)
            {
                MixerIntControl mic = mc as MixerIntControl;
                mic.Value = mic.Maximum;
                break;
            }
            else if (mc is MixerListControl)
            {
                MixerListControl mlc = dl.Controls[0] as MixerListControl;
                MixerLine ml = mlc.Lines[mlc.Value];
                foreach (MixerControl ctrl in ml.Controls)
                {
                    if (ctrl is MixerIntControl)
                    {
                        MixerIntControl mic = ctrl as MixerIntControl;
                        mic.Value = mic.Maximum;
                        break;
                    }
                }
            }
        }
    }
}

Up

117. Detecting audio silence in WAV files using C#

        private static void SkipSilent(string fileName, short silentLevel)
        {
            WaveReader wr = new WaveReader(File.OpenRead(fileName));
            IntPtr format = wr.ReadFormat();
            WaveWriter ww = new WaveWriter(File.Create(fileName + ".wav"), 
                AudioCompressionManager.FormatBytes(format));
            int i = 0;
            while (true)
            {
                byte[] data = wr.ReadData(i, 1);
                if (data.Length == 0)
                {
                    break;
                }
                if (!AudioCompressionManager.CheckSilent(format, data, silentLevel))
                {
                    ww.WriteData(data);
                }
            }
            ww.Close();
            wr.Close();
        }

Up

118. Getting duration of audio file C#

        DsReader dr = new DsReader("your audio file");
        int durationInMS = dr.GetDurationInMS();
        dr.Close();

Up

119. Covert a A-Law mono .vox file to .wav file in c# .net. Vox file encoding is: A-Law mono at 8000 HZ.

   static void Raw2Wav(string fileName)
    {
        WaveFormat wf = new WaveFormat();
        wf.wFormatTag = AudioCompressionManager.ALawFormatTag;
        wf.nChannels = 1;
        wf.nSamplesPerSec = 8000;
        FormatDetails[] formatList = AudioCompressionManager.GetFormatList(wf);
        IntPtr format = formatList[0].FormatHandle;
        RawReader rr = new RawReader(File.OpenRead(fileName), format);
        byte[] data = rr.ReadData();
        rr.Close();
        WaveWriter ww = new WaveWriter(File.Create(fileName + ".wav"), 
            AudioCompressionManager.FormatBytes(format));
        ww.WriteData(data);
        ww.Close();
    }

Up

120. How to pass PCM 8bit audio data in Echo filter?

You need to convert it to PCM 16 bit using AudioCompressionManager.ToPcm16Bit method first. See code below
        string waveFile = @"in.wav"; 
        EchoAudioEffect echo = AudioEffect.CreateEchoAudioEffect();
        WaveReader wr = new WaveReader(File.OpenRead(waveFile));
        IntPtr format = wr.ReadFormat();
        byte[] data = wr.ReadData();
        wr.Close();
        IntPtr formatPcm16Bit = IntPtr.Zero;
        byte[] dataPcm16Bit = null;
        AudioCompressionManager.ToPcm16Bit(format, data, ref formatPcm16Bit, ref dataPcm16Bit);
        formatPcm16Bit = format;
        dataPcm16Bit = data;
        if (echo.ProcessInPlace(formatPcm16Bit, dataPcm16Bit))
        {
            PlayerEx plex = new PlayerEx();
            plex.OpenPlayer(formatPcm16Bit);
            plex.AddData(dataPcm16Bit);
        }

Up

121. How to convert Dialogic adpcm vox file 6000 samples per second to wave gsm?

    private static void Vox2Gsm(string voxFile, string wavFile)
    {
        int samplesPerSec = 6000;
        IntPtr format = AudioCompressionManager.GetPcmFormat(1, 16, samplesPerSec);
        MemoryStream ms = new MemoryStream();
        BinaryReader br = new BinaryReader(File.OpenRead(voxFile));
        WaveWriter ww = new WaveWriter(ms, AudioCompressionManager.FormatBytes(format));
        Vox.Vox2Wav(br, ww);
        br.Close();
        WaveReader wr = new WaveReader(ms);
        byte[] data = wr.ReadData();
        wr.Close();
        ww.Close();
        IntPtr formatGsm = AudioCompressionManager.GetCompatibleFormat(format, AudioCompressionManager.Gsm610FormatTag);
        byte[] dataGsm = AudioCompressionManager.Convert(format, formatGsm, data, false);
        WaveWriter wwGsm = new WaveWriter(File.Create(wavFile), AudioCompressionManager.FormatBytes(formatGsm));
        wwGsm.WriteData(dataGsm);
        wwGsm.Close();
    }

Up

122. How can I play an MP3 from a memory stream in C#?

        //Memory stream with mp3 audio data
        MemoryStream ms = new MemoryStream();
        Mp3Reader mr = new Mp3Reader(ms);
        PlayerEx plex = new PlayerEx();
        plex.OpenPlayer(mr.ReadFormat());
        plex.AddData(mr.ReadData());
        plex.StartPlay();

Up

123. Is there a way to determine the duration of a wav file that's held in a MemoryStream?

MemoryStream ms = ...
WaveReader wr = new WaveReader(ms);
int durationInMS = wr.GetDurationInMS();
wr.Close();

Up

124. How to add metadata to WAV file?

See
ID3 tags for Wave files article

Up

125. C# resample audio from 8khz to 44.1/48khz.

        static void Resample(string fileName)
        {
            IntPtr formatNew = AudioCompressionManager.GetPcmFormat(2, 16, 44100);
            WaveReader wr = new WaveReader(File.OpenRead(fileName));
            IntPtr format = wr.ReadFormat();
            byte[] data = wr.ReadData();
            wr.Close();
            //PCM 8000 Hz -> PCM 44100
            byte[] dataNew = AudioCompressionManager.Resample(format, data, formatNew);
            WaveWriter ww = new WaveWriter(File.Create(fileName + ".wav"),
                AudioCompressionManager.FormatBytes(formatNew));
            ww.WriteData(dataNew);
            ww.Close();
        }

Up

126. How to use Alvas.Audio to detect any sounds?

            if (!AudioCompressionManager.CheckSilent(format, data, silentLevel))
            {
                //have sound
            }

Up

127. Extract wav file from video file

        static void ExtractWavFromVideoFile(string fileName)
        {
            //For .Avi file
            AviReader ar = new AviReader(File.OpenRead(fileName));
            if (ar.HasAudio)
            {
                IntPtr format = ar.ReadFormat();
                byte[] data = ar.ReadData();
                WaveWriter ww = new WaveWriter(File.Create(fileName + ".wav"),
                    AudioCompressionManager.FormatBytes(format));
                ww.WriteData(data);
                ww.Close();
            }
            ar.Close();
            //For any media file
            DsReader dr = new DsReader(fileName);
            if (dr.HasAudio)
            {
                IntPtr format = dr.ReadFormat();
                byte[] data = dr.ReadData();
                WaveWriter ww = new WaveWriter(File.Create(fileName + ".wav"),
                    AudioCompressionManager.FormatBytes(format));
                ww.WriteData(data);
                ww.Close();
            }
            dr.Close();
        }

Up

128. I’m trying to play Vox files, which are encoded in U-Law, byte order Little-endian, 1 channel, with a sample rate of 8kHz. These are raw files, so I need to be able to hard set these attributes for the files to play. Is this possible in your application?

        private void PlayVox(string voxFile)
        {
            //CCITT u-Law, 8000 Hz, 1 channels
            WaveFormat wf = new WaveFormat();
            wf.wFormatTag = AudioCompressionManager.MuLawFormatTag;
            wf.nChannels = 1;
            wf.nSamplesPerSec = 8000;
            FormatDetails[] formatList = AudioCompressionManager.GetFormatList(wf);
            IntPtr format = formatList[0].FormatHandle;
            RawReader rr = new RawReader(File.OpenRead(voxFile), format);
            byte[] data = rr.ReadData();
            rr.Close();
            PlayerEx plex = new PlayerEx();
            plex.OpenPlayer(format);
            plex.AddData(data);
            plex.StartPlay();
        }

Up

129. I am having trouble converting a 6000 hz Vox file to a 16 kbit MP3.

        private static void Vox2Mp3(string fileName)
        {
            BinaryReader br = new BinaryReader(File.OpenRead(fileName));
            MemoryStream ms = new MemoryStream();
            IntPtr format = AudioCompressionManager.GetPcmFormat(1, 16, 6000);
            WaveWriter ww = new WaveWriter(ms, AudioCompressionManager.FormatBytes(format));
            Vox.Vox2Wav(br, ww);
            br.Close();
            WaveReader wr = new WaveReader(ms);
            const int sampleRate = 16000;
            IntPtr format16000 = AudioCompressionManager.GetPcmFormat(1, 16, sampleRate);
            byte[] data16000 = AudioCompressionManager.Resample(wr, format16000);
            wr.Close();
            FormatDetails[] compatibleFormatList = AudioCompressionManager.GetCompatibleFormatList(format);
            IntPtr mp3Format = AudioCompressionManager.GetMp3Format(1, 16, sampleRate);
            byte[] mp3Data = AudioCompressionManager.Convert(format16000, mp3Format, data16000, false);
            Mp3Writer mw = new Mp3Writer(File.Create(fileName + ".mp3"));
            mw.WriteData(mp3Data);
            mw.Close();
        }

Up

130. I am designing a sound editor and i was wondering that while a song is playing using your software would it record anything that is playing on the sound card in Windows XP?

You need select "Stereo Mix" instead of "Microphone".
        void Record()
        {
            RecorderEx recEx = new RecorderEx();
            SelectStereoMix(recEx);
            recEx.Format = AudioCompressionManager.GetPcmFormat(1, 16, 44100);
            recEx.StartRecord();
        }

        static void SelectStereoMix(RecorderEx recEx)
        {
            Mixer m = new Mixer();
            m.MixerNo = recEx.GetMixerNo();
            MixerControl[] mcArr = m.GetDestination(Mixer.Recording).Controls;
            foreach (MixerControl ctrl in mcArr)
            {
                if (ctrl is MixerListControl)
                {
                    MixerListControl volumeControl = ctrl as MixerListControl;
                    for (int i = 0; i < volumeControl.Lines.Length; i++)
                    {
                        MixerLine ml = volumeControl.Lines[i];
                        if (ml.ShortName == "Stereo Mix")
                        {
                            volumeControl.Value = i;
                            break;
                        }
                    }
                    break;
                }
            }
        }

Up

131. I have noticed is that when the faded in track is joined to another segment of track, there is a slight skip.

You first need to decode your mp3 file to PCM and encode to Mp3 format at the end of transformation.
    Private Sub PlayAudioFile(ByVal FileName As String)

        Dim ms As New MemoryStream
        Dim mr As Mp3Reader = New Mp3Reader(File.OpenRead(FileName))
        Dim formatMp3 As IntPtr = mr.ReadFormat()
        Dim formatPcm As IntPtr = AudioCompressionManager.GetCompatibleFormat(formatMp3, _
            AudioCompressionManager.PcmFormatTag)
        Dim ww As New WaveWriter(ms, AudioCompressionManager.FormatBytes(formatPcm))
        AudioCompressionManager.Convert(mr, ww, False)
        mr.Close()
        Dim wr As New WaveReader(ms)

        Dim AudioTrackDuration As Long = 0
        Dim Duration As Long = wr.GetDurationInMS

        AudioTrackDuration = TimeSpan.FromMilliseconds(Duration).TotalSeconds

        Dim FadeOutStart As Long = AudioTrackDuration - 5
        Dim format As IntPtr = wr.ReadFormat()

        Dim data1 As Byte() = wr.ReadData(0, 5)
        Dim data2 As Byte() = wr.ReadData(5, FadeOutStart)
        Dim data3 As Byte() = wr.ReadData(FadeOutStart, 5)

        wr.Close()

        Dim data11 As Byte() = AudioCompressionManager.Fade(format, data1, True)
        Dim data33 As Byte() = AudioCompressionManager.Fade(format, data3, False)

        Dim mw As New Mp3Writer(File.Create("test.mp3"))

        mw.WriteData(AudioCompressionManager.Convert(formatPcm, formatMp3, data11, False))
        mw.WriteData(AudioCompressionManager.Convert(formatPcm, formatMp3, data2, False))
        mw.WriteData(AudioCompressionManager.Convert(formatPcm, formatMp3, data33, False))

        mw.Close()
    End Sub

Up

132. Could you send me a example how to convert IEEE Floating Point Audio (received the captured data as floating point) to WAV?

For example you need convert from IEEE 32 bit floating point 44100 Hz stereo to PCM 16 bit 44100 Hz stereo (WAV)
private static void Float2Pcm(float[] dataFloat)
{
    const int floatSize = 4;
    byte[] data = new byte[dataFloat.Length * floatSize];
    Buffer.BlockCopy(dataFloat, 0, data, 0, data.Length);
    IntPtr formatFloat = AudioCompressionManager.GetFloat32Format(2, 44100);
    IntPtr formatPcm = AudioCompressionManager.GetPcmFormat(2, 16, 44100);
    byte[] dataPcm = AudioCompressionManager.Resample(formatFloat, data, formatPcm);
}
where formatPcm and dataPcm is output format and data.

Up

133. How to convert .wav to .aiff?

static void Wav2Aiff(string inFile)
{
    WaveReader wr = new WaveReader(File.OpenRead(inFile));
    IntPtr inFormat = wr.ReadFormat();
    IntPtr outFormat = AudioCompressionManager.GetCompatibleFormat(inFormat, 
        AudioCompressionManager.PcmFormatTag);
    string outFile = inFile + ".aif";
    AiffWriter aw = new AiffWriter(File.Create(outFile), outFormat);
    byte[] outData = AudioCompressionManager.Convert(inFormat, outFormat, wr.ReadData(), false);
    aw.WriteData(outData);
    wr.Close();
    aw.Close();
}

Up

134. How to convert audio file to mp3 with specified bitrate?

        static void ToBitRate(IAudioReader mr, int bitrate, string outMp3)
        {
            IntPtr formatOld = mr.ReadFormat();
            IntPtr formatPcm = AudioCompressionManager.GetCompatibleFormat(formatOld, 
				AudioCompressionManager.PcmFormatTag);
            FormatDetails[] fdArr = AudioCompressionManager.GetCompatibleFormatList(formatPcm, true);
            foreach (FormatDetails fd in fdArr)
            {
                WaveFormat wf = AudioCompressionManager.GetWaveFormat(fd.FormatHandle);
                if (wf.wFormatTag == AudioCompressionManager.MpegLayer3FormatTag)
                {
                    if (bitrate == wf.nAvgBytesPerSec * 8)
                    {
                        IntPtr format = fd.FormatHandle;
                        byte[] data = AudioCompressionManager.ToFormat(mr, format);
                        using (Mp3Writer mw = new Mp3Writer(File.Create(outMp3)))
                        {
                            mw.WriteData(data);
                        }
                    }
                }
            }
        }

        static void Main(string[] args)
        {
            string fileName = @"d:\Work\Attachments\tmn.mp3";
            using (Mp3Reader mr = new Mp3Reader(File.OpenRead(fileName)))
            {
                ToBitRate(mr, 256000, fileName + ".mp3");
            }
        }

Up

135. Does anyone know a simple way of converting a mp4 file to an ogg file?

        static void Mp4ToOgg(string fileName)
        {
            DsReader dr = new DsReader(fileName);
            if (dr.HasAudio)
            {
                string waveFile = fileName + ".wav";
                WaveWriter ww = new WaveWriter(File.Create(waveFile),
                    AudioCompressionManager.FormatBytes(dr.ReadFormat()));
                ww.WriteData(dr.ReadData());
                ww.Close();
                dr.Close();
                try
                {
                    Sox.Convert(@"sox.exe", waveFile, waveFile + ".ogg", SoxAudioFileType.Ogg);
                }
                catch (SoxException ex)
                {
                    throw;
                }
            }
        }

Up

136. How to improve quality of the converted mp3-files from wav-files with low bitrate in VB?

Try any of the functions listed below
    Public Function Wav2Mp3(ByVal inFile As String) As Byte()
        Dim data As Byte() = Nothing
        Try
            Dim oDsReader1 As New DsReader(inFile)
            Dim originalAudioFormat As IntPtr = oDsReader1.ReadFormat()
            Dim waveReaderData As Byte() = oDsReader1.ReadData()
            oDsReader1.Close()

            Dim wf As WaveFormat = AudioCompressionManager.GetWaveFormat(originalAudioFormat)
            Dim resampleFormat As IntPtr = AudioCompressionManager.GetPcmFormat(wf.nChannels, wf.wBitsPerSample, wf.nSamplesPerSec * 2)
            Dim resampleData As Byte() = AudioCompressionManager.Resample(originalAudioFormat, waveReaderData, resampleFormat)

            Dim mp3Format As IntPtr = AudioCompressionManager.GetCompatibleFormat(resampleFormat, AudioCompressionManager.MpegLayer3FormatTag)
            data = AudioCompressionManager.Convert(resampleFormat, mp3Format, resampleData, False)
            Dim FileWrite As New Mp3Writer(File.Create(inFile + ".mp3"))
            FileWrite.WriteData(data)
            FileWrite.Close()
        Catch ex As Exception
            Throw ex
        End Try
        Return data
    End Function

    Public Function Wav2Mp3_2(ByVal inFile As String) As Byte()
        Dim data As Byte() = Nothing
        Try
            Dim oFile1 As FileStream = File.OpenRead(inFile)
            Dim oWaveReader1 As New WaveReader(oFile1)
            Dim originalAudioFormat As IntPtr = oWaveReader1.ReadFormat()

            Dim wf As WaveFormat = AudioCompressionManager.GetWaveFormat(originalAudioFormat)
            Dim resampleFormat As IntPtr = AudioCompressionManager.GetPcmFormat(wf.nChannels, 16, wf.nSamplesPerSec * 2)
            Dim resampleData As Byte() = AudioCompressionManager.ToFormat(oWaveReader1, resampleFormat)
            oWaveReader1.Close()

            Dim mp3Format As IntPtr = AudioCompressionManager.GetCompatibleFormat(resampleFormat, AudioCompressionManager.MpegLayer3FormatTag)
            data = AudioCompressionManager.Convert(resampleFormat, mp3Format, resampleData, False)
            Dim FileWrite As New Mp3Writer(File.Create(inFile + ".mp3"))
            FileWrite.WriteData(data)
            FileWrite.Close()
        Catch ex As Exception
            Throw ex
        End Try
        Return data
    End Function

Up

137. How to play WAV audio file from Resources in c#?

  Stream str = Properties.Resources.mySoundFile;
  RecordPlayer rp = new RecordPlayer();
  rp.Open(new WaveReader(str));
  rp.Play();

Up

138. How convert wav pcm 44100 to a-law 8bit mono in c#?

        static void PcmToAlaw(string fileName)
        {
            WaveReader wr = new WaveReader(File.OpenRead(fileName));
            IntPtr pcmFormat = wr.ReadFormat();
            FormatDetails[] fdArr = AudioCompressionManager.GetCompatibleFormatList(pcmFormat, true);
            foreach (FormatDetails fd in fdArr)
	        {
                WaveFormat wf = AudioCompressionManager.GetWaveFormat(fd.FormatHandle);
                if (wf.wFormatTag == AudioCompressionManager.ALawFormatTag && wf.nChannels == 1)
                {
                    IntPtr alawFormat = fd.FormatHandle;
                    byte[] alawData = AudioCompressionManager.ToFormat(wr, alawFormat);
                    WaveWriter ww = new WaveWriter(File.Create(fileName + ".wav"),
                        AudioCompressionManager.FormatBytes(alawFormat));
                    ww.WriteData(alawData);
                    ww.Close();
                    break;
                }
            }
        }

Up

139. How to convert PCM 8 bit 8000 wav file to mp3?

        static void ToMp3(string fileName)
        {
            WaveReader wr = new WaveReader(File.OpenRead(fileName));
            IntPtr format = wr.ReadFormat();
            byte[] data = wr.ReadData();
            byte[] dataMp3 = AudioCompressionManager.Wave2Mp3(format, data);
            wr.Close();
            var mw = new Mp3Writer(File.Create(fileName + ".mp3"));
            mw.WriteData(dataMp3);
            mw.Close();
        }

Up

140. Whether Alvas.Audio can play then received from ALAW BYTE[] from the network IN C#; Each byte[] has 160 bytes,Receiving 50 packets per second

using System;
using System.Windows.Forms;
using Alvas.Audio;

namespace WfAlaw
{
    public partial class Form1 : Form
    {
        PlayerEx plex = new PlayerEx();

        void button1_Click(object sender, EventArgs e)
        {
            WaveFormat wf = new WaveFormat();
            wf.nChannels = 1;
            wf.nSamplesPerSec = 8000;
            wf.wFormatTag = AudioCompressionManager.ALawFormatTag;
            var list = AudioCompressionManager.GetFormatList(wf);
            IntPtr format = list[0].FormatHandle;
            plex.OpenPlayer(format);
            plex.StartPlay();
        }

        void timer1_Tick(object sender, EventArgs e)
        {
            plex.AddData(bytes);//Each byte[] has 160 bytes,Receiving 50 packets per second
        }
    }
}

Up

141. Is there a way to check to see if there are any recording devices on the system. I was wondering if there is a way to first check if there are recording devices before calling the StartRecord method.

            if (RecorderEx.RecorderCount > 0)
            {
                //
            }

Up

142. The sample code you sent below is working great. Is there a way to increase the quality of the final MP3 and if so, how would the code below change?

            string wavFile = @"C:\work\CR598_4.wav";
            string mp3File = wavFile + ".mp3";
            ConvertWavToMP3(wavFile, mp3File);

        public static string ConvertWavToMP3(string inFile, string mp3File)
        {
            string result = "Ok";

            WaveReader wr = new WaveReader(File.OpenRead(inFile));
            IntPtr format = wr.ReadFormat();
            byte[] data = wr.ReadData();
            wr.Close();
            WaveFormat wf = AudioCompressionManager.GetWaveFormat(format);
            if (wf.wFormatTag != AudioCompressionManager.PcmFormatTag)//Decode if not PCM data
            {
                Decode2Pcm(ref format, ref data, ref wf);
            }
            wf = AudioCompressionManager.GetWaveFormat(format);
            //samplesPerSec of your file is 8000
            int samplesPerSec = 11025;//or 12000, 16000, 22050, 24000, 32000, 44100, 48000 
            IntPtr formatResample = AudioCompressionManager.GetPcmFormat(wf.nChannels, wf.wBitsPerSample, samplesPerSec); 
            byte[] dataResample = AudioCompressionManager.Resample(format, data, formatResample);
            format = formatResample;
            data = dataResample;
            IntPtr webFormat = AudioCompressionManager.GetCompatibleFormat(format,
                AudioCompressionManager.MpegLayer3FormatTag);
            byte[] buffer = AudioCompressionManager.Convert(format, webFormat, data, false);
            Mp3Writer bw = new Mp3Writer(File.Create(mp3File));
            bw.WriteData(buffer);
            bw.Close();

            return result;
        }

        private static void Decode2Pcm(ref IntPtr format, ref byte[] data, ref WaveFormat wf)
        {
            IntPtr formatPcm16Bit = IntPtr.Zero;
            byte[] dataPcm16Bit = null;
            AudioCompressionManager.ToPcm16Bit(format, data, ref formatPcm16Bit, ref dataPcm16Bit);
            wf = AudioCompressionManager.GetWaveFormat(formatPcm16Bit);
            format = formatPcm16Bit;
            data = dataPcm16Bit;
        }

Up

143. Can Alvas.Audio convert an MP3 to a wav file with this codec/format: Codec: IMA WAV ADPCM Channels: Mono Sample Rate: 8000 Hz Bits per sample: 16   If so, do you have any sample code for that?

            Mp3ToIma(@"c:\work\test.mp3");
        /*
Codec: IMA WAV ADPCM
Channels: Mono
Sample Rate: 8000 Hz
Bits per sample: 16
         */
        static void Mp3ToIma(string fileName)
        {
            using (Mp3Reader mr = new Mp3Reader(File.OpenRead(fileName)))
            {
                IntPtr mp3Format = mr.ReadFormat();
                byte[] mp3Data = mr.ReadData();
                IntPtr pcmFormat = AudioCompressionManager.GetCompatibleFormat(mp3Format, AudioCompressionManager.PcmFormatTag);
                byte[] pcmData = AudioCompressionManager.Convert(mp3Format, pcmFormat, mp3Data, false);
                IntPtr pcmFormat8000 = AudioCompressionManager.GetPcmFormat(1, 16, 8000);
                byte[] pcmData8000 = AudioCompressionManager.Resample(pcmFormat, pcmData, pcmFormat8000);
                IntPtr imaFormat = AudioCompressionManager.GetCompatibleFormat(pcmFormat8000, AudioCompressionManager.ImaAdpcmFormatTag);
                byte[] imaData = AudioCompressionManager.Convert(pcmFormat8000, imaFormat, pcmData8000, false);
                using (WaveWriter ww = new WaveWriter(File.Create(fileName + ".wav"), AudioCompressionManager.FormatBytes(imaFormat)))
                {
                    ww.WriteData(imaData);
                }
            }
        }

Up

144. The issue we have is that the original file is captured from a dialogic telephony card in 8k 8bit mono format and is low-quality audio with a lot of background noise. The mp3 file that Alvas.Audio creates by default is a lower quality file. Is there a way to improve that? We use Visual Basic.Net.

        WaveToMp3Max("c:\work\2015\8k8bitpcm.wav")
        
    Private Sub NewSampleRate(ByRef format As IntPtr, ByRef data() As Byte)
        Dim wf As WaveFormat = AudioCompressionManager.GetWaveFormat(format)
        Dim format2 As IntPtr = AudioCompressionManager.GetPcmFormat(wf.nChannels, 16, wf.nSamplesPerSec * 2)
        Dim data2 As Byte() = AudioCompressionManager.Resample(format, data, format2)
        format = format2
        data = data2
    End Sub
        
    Private Sub WaveToMp3Max(waveFile As String)
        Dim wr As New WaveReader(File.OpenRead(waveFile))
        Dim format As IntPtr = wr.ReadFormat()
        Dim data As Byte() = wr.ReadData()
        wr.Close()
        NewSampleRate(format, data)
        Dim brMax As Integer = 0
        Dim dict As New Dictionary(Of Integer, IntPtr)
        Dim fdArray As FormatDetails() = AudioCompressionManager.GetCompatibleFormatList(format, True)
        For Each fd As FormatDetails In fdArray
            If fd.FormatTag = AudioCompressionManager.MpegLayer3FormatTag Then
                Dim wf As WaveFormat = AudioCompressionManager.GetWaveFormat(fd.FormatHandle)
                brMax = Math.Max(brMax, wf.nAvgBytesPerSec)
                dict(brMax) = fd.FormatHandle
            End If
        Next
        Dim dataMp3 As Byte() = AudioCompressionManager.Convert(format, dict(brMax), data, False)
        Dim mw As New Mp3Writer(File.Create(waveFile & ".mp3"))
        mw.WriteData(dataMp3)
        mw.Close()
    End Sub

Up
Blog :: Contact Us :: Copyright © 1998-2023 Alvas.Net. All rights reserved