Search code examples
c#.netazure-storagenaudiolame

How convert audio aiff to MP3 using Memory stream, NAudio and LameMP3


I try to convert aiff audio file from IFormFile to MP3 and upload it to Azure Storage. I don't understand how works memory streams with NAudio... I don't want to copy file in a temp file but only using streams. Is it possible ?

using (var retMs = new MemoryStream())
{
   file.CopyTo(retMs);
   var fileBytes = retMs.ToArray();
   string s = Convert.ToBase64String(fileBytes);

    using (var ms = new MemoryStream(fileBytes))
    using (var reader = new AiffFileReader(ms))
    using (var writer = new LameMP3FileWriter(retMs, reader.WaveFormat, 128))
    {
       reader.CopyTo(writer);

       var result = await _blobService.UploadFileBlobAsync(
                              reader,
                              "audio/mpeg3",
                              "fr2.mp3");

       toReturn = result.AbsoluteUri; 
      }
                                
   }

Solution

  • I think the demo code below could be helpful for you.

    using Azure.Storage.Blobs;
    using NAudio.Lame;
    using NAudio.Wave;
    using System;
    using System.IO;
    
    namespace blobUpload
    {
        class Program
        {
            static void Main(string[] args)
            {
                string containerName = "<container name>";
                string blobName = "test.mp3";
                string storageConnStr = "<storage account conn str>";
    
                var blobServiceClient = new BlobServiceClient(storageConnStr);
                var blobClient = blobServiceClient.GetBlobContainerClient(containerName).GetBlobClient(blobName);
    
                using (var retMs = new MemoryStream())
                {
                    FileStream inputfileStream = new FileStream(@"<aiff file path>", FileMode.Open, FileAccess.Read);
                    inputfileStream.CopyTo(retMs);
                    var fileBytes = retMs.ToArray();
                    
                    var bytes = ConvertWavToMp3(fileBytes);
    
                    blobClient.UploadAsync(new MemoryStream(bytes)).GetAwaiter().GetResult();
    
                }
    
            }
    
            public static byte[] ConvertWavToMp3(byte[] wavFile)
            {
    
                using (var retMs = new MemoryStream())
                using (var ms = new MemoryStream(wavFile))
                using (var rdr = new AiffFileReader(ms))
                using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, 128))
                {
                    rdr.CopyTo(wtr);
                    return retMs.ToArray();
                }
    
           }
        }
    

    Result : enter image description here

    I have tested on my side, this .MP3 file could be played perfectly.