-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathAudioConversionHelper.cs
More file actions
61 lines (55 loc) · 2.25 KB
/
Copy pathAudioConversionHelper.cs
File metadata and controls
61 lines (55 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using NAudio.Lame;
using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RoleplayingVoiceCore {
public static class AudioConversionHelper {
private static string? _nativeLibrarySearchPath;
public static string? NativeLibrarySearchPath {
get => _nativeLibrarySearchPath;
set => _nativeLibrarySearchPath = value;
}
private static void EnsureLameNativeLibraryLoaded() {
var searchPaths = new List<string>();
if (!string.IsNullOrEmpty(_nativeLibrarySearchPath)) {
searchPaths.Add(_nativeLibrarySearchPath);
}
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
if (!string.IsNullOrEmpty(baseDirectory)) {
searchPaths.Add(baseDirectory);
}
LameDLL.LoadNativeDLL(searchPaths.Distinct(StringComparer.OrdinalIgnoreCase).ToArray());
}
public static int GetSimpleHash(string s) {
return s.Select(a => (int)a).Sum();
}
public static async Task<byte[]> WaveStreamToMp3Bytes(Stream wavStream) {
EnsureLameNativeLibraryLoaded();
wavStream.Position = 0;
MemoryStream mp3Stream = new MemoryStream();
using (WaveFileReader waveFileReader = new WaveFileReader(wavStream)) {
using (var resampler = new MediaFoundationResampler(waveFileReader, 44100)) {
using (var mp3Writer = new LameMP3FileWriter(mp3Stream, resampler.WaveFormat, 64)) {
resampler.ResamplerQuality = 60;
var arr = new byte[128];
while (resampler.Read(arr, 0, arr.Length) > 0) {
// Send stream to the provider
await mp3Writer.WriteAsync(arr, 0, arr.Length);
}
await mp3Writer.FlushAsync();
}
}
}
mp3Stream.Position = 0;
var bytes = mp3Stream.ToArray();
if (bytes.Length > 0) {
return bytes;
} else {
return null;
}
}
}
}