Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Audio Exporting .mp3 file from audioclip

Discussion in 'Audio & Video' started by migueltuliompg, Jun 19, 2019.

  1. migueltuliompg

    migueltuliompg

    Joined:
    Feb 12, 2018
    Posts:
    56
    Hey all!

    I'm working on an awesome editor for my rhythm-based dungeon crawler!

    One of the main features is the ability to import and trim custom music then save the level with that music in the save file. So far you can import and trim the music and it plays and loops properly, but I can't seem to find an easy way to export an mp3 file from an AudioClip.

    The closest I came was a script that converts an audioclip from a wav to and mp3 then saves it, but when I try that with an mp3 the end gets cut off.

    Code (CSharp):
    1. /*                    GNU GENERAL PUBLIC LICENSE
    2.                        Version 3, 29 June 2007
    3.  
    4. Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
    5. Everyone is permitted to copy and distribute verbatim copies
    6. of this license document, but changing it is not allowed.
    7.  
    8. */
    9.  
    10. /*---------------------- BeatUp (C) 2016-------------------- */
    11.  
    12.  
    13. using UnityEngine;
    14. using System.Collections;
    15. using System.Collections.Generic;
    16. using System.IO;
    17. using System;
    18. using NAudio.Wave;
    19. using NAudio.Lame;
    20.  
    21. public static class EncodeMP3
    22. {
    23.  
    24.  
    25.     public static void convert (AudioClip clip, string path, int bitRate)
    26.     {
    27.  
    28.         if (!path.EndsWith (".mp3"))
    29.             path = path + ".mp3";
    30.        
    31.         ConvertAndWrite (clip, path, bitRate);
    32.  
    33.     }
    34.  
    35.  
    36.     //  derived from Gregorio Zanon's script
    37.     private static void ConvertAndWrite (AudioClip clip, string path, int bitRate)
    38.     {
    39.  
    40.         float[] samples = new float[clip.samples * clip.channels];
    41.  
    42.         clip.GetData (samples, 0);
    43.  
    44.         Debug.Log(samples.Length);
    45.  
    46.         Int16[] intData = new Int16[samples.Length];
    47.         //converting in 2 float[] steps to Int16[], //then Int16[] to Byte[]
    48.  
    49.         Byte[] bytesData = new Byte[samples.Length * 2];
    50.         //bytesData array is twice the size of
    51.         //dataSource array because a float converted in Int16 is 2 bytes.
    52.  
    53.         float rescaleFactor = 32767; //to convert float to Int16
    54.  
    55.         for (int i = 0; i < samples.Length; i++) {
    56.             intData[i] = (short)(samples[i] * rescaleFactor);
    57.             Byte[] byteArr = new Byte[2];
    58.             byteArr = BitConverter.GetBytes(intData[i]);
    59.             byteArr.CopyTo(bytesData, i * 2);
    60.         }
    61.  
    62.         File.WriteAllBytes (path, ConvertWavToMp3 (bytesData, bitRate));
    63.     }
    64.  
    65.     public static byte[] GetClipData(AudioClip _clip)
    66.     {
    67.         //Get data
    68.         float[] floatData = new float[_clip.samples * _clip.channels];
    69.         _clip.GetData(floatData, 0);
    70.  
    71.         //convert to byte array
    72.         byte[] byteData = new byte[floatData.Length * 4];
    73.         Buffer.BlockCopy(floatData, 0, byteData, 0, byteData.Length);
    74.  
    75.         return (byteData);
    76.     }
    77.  
    78.  
    79.  
    80.     private static byte[] ConvertWavToMp3 (byte[] bytes, int bitRate)
    81.     {
    82.  
    83.         var retMs = new MemoryStream ();
    84.         var ms = new MemoryStream (bytes);
    85.         var rdr = new RawSourceWaveStream (ms, new WaveFormat ());
    86.         var wtr = new LameMP3FileWriter (retMs, rdr.WaveFormat, bitRate);
    87.  
    88.         rdr.CopyTo (wtr);
    89.         return retMs.ToArray ();
    90.  
    91.  
    92.  
    93.     }
    94. }

    It doesn't cut off the end if I just save the rawdata...

    Code (CSharp):
    1. File.WriteAllBytes (path, GetClipData(clip));
    But then it's not compressed which defeats the purpose of an mp3 file.
    If I convert it instead...

    Code (CSharp):
    1. File.WriteAllBytes (path, ConvertWavToMp3 (bytesData, bitRate));
    it ends up missing the very end.

    I would very much like to be able to just import an mp3, edit it, and then save it as an mp3.

    Any ideas?
     
  2. Deleted User

    Deleted User

    Guest

    The LameMP3FileWriter has an internal buffer AFAIK that is encoded if the buffer is full. So could be that you need to call Flush() before return.
     
    migueltuliompg and TilleyTech like this.
  3. migueltuliompg

    migueltuliompg

    Joined:
    Feb 12, 2018
    Posts:
    56
    It worked! Thanks a lot! :)
     
  4. Roxydoce

    Roxydoce

    Joined:
    Oct 10, 2021
    Posts:
    9
    UNITY EXPORT A AUDIO FILE IN RUNTIME, to the downloads file on the player PC. Anyone can help me?

    So far I can record the audio as an mp3 but I cant find a solution that when I press stop recording, the file its automatedly exported to the downloads file.

    Any expert here that can help me out PLEASE!!!!!!!
     
  5. SeventhString

    SeventhString

    Unity Technologies

    Joined:
    Jan 12, 2023
    Posts:
    373
    Try this!

    Code (CSharp):
    1. byte[] yourAudioData = GetYourAudioData();
    2.  
    3. #if UNITY_EDITOR
    4. // In the Unity Editor, save the file to the Assets folder
    5. string savePath = Path.Combine(Application.dataPath, "GeneratedAudioFile.wav");
    6. #else
    7. // In a build, save the file to the user's persistent data folder
    8. string savePath = Path.Combine(Application.persistentDataPath, "GeneratedAudioFile.wav");
    9. #endif
    10.  
    11. // Write the audio data to the file
    12. File.WriteAllBytes(savePath, audioData);
     
    Roxydoce and Doomlaser like this.
  6. deanroberson

    deanroberson

    Joined:
    Dec 9, 2023
    Posts:
    1
    Thank you. I was having the same issues when I was trying to import audio clips. Now everything is working.
    IG Audio Download Tool
     
    Last edited: Dec 9, 2023