Search code examples
c#filestreamnaudiofilewriter

Why cant i play the File externally while my Application is open?


I managed to convert a wav file to a mp3 file. But while my Application is running, it does only freeze VLC Media Player (Bad File descriptor) When i close my Application, it will play just fine.

public void ConvertWavToMp3(string filename)
    {
        LameMP3FileWriter mpFileWriter;
        if (File.Exists(Path.Combine(filename.Split('.').FirstOrDefault() + ".mp3"))) File.Delete(Path.Combine(filename.Split('.').FirstOrDefault() + ".mp3"));
        using (WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(new WaveFileReader(filename)))            
        using (mpFileWriter = new LameMP3FileWriter(File.Create(Path.Combine(filename.Split('.').FirstOrDefault() + ".mp3")), waveStream.WaveFormat, LAMEPreset.ABR_320))
        {
            byte[] bytes = new byte[waveStream.Length];
            waveStream.Position = 0;
            waveStream.Read(bytes, 0, (int)waveStream.Length);
            mpFileWriter.Write(bytes, 0, bytes.Length);
            mpFileWriter.Flush();


        }
        if (mpFileWriter != null)
        {
            mpFileWriter.Dispose();
            mpFileWriter.Close();
            mpFileWriter = null;
        }
        else Console.WriteLine("file writer was null");
        lblstatus.Text = "Ready";
        lblstatus.ForeColor = System.Drawing.Color.DarkGreen;
    }

As you can see, i close and dispose the file, but this doesnt work. The Error stays. The File itself is fine, but the App is not allowed to run or it will not play. Strange. Hopefully you can help me, Sincelery, TheSkilluminati PS: I am not an english-native speaker, so i apologize for any issues in the text :)


Solution

  • I'm not completely sure, but you need to close and dispose the FileStream create by File.Create(Path.Combine(filename.Split('.').FirstOrDefault() + ".mp3")

    just add another using to your code that will dispose the FileStream

    string filePath = Path.Combine(filename.Split('.').FirstOrDefault() + ".mp3";
    
    using(FileStream fs = File.Create(filePath))
    using (mpFileWriter = new LameMP3FileWriter(fs), waveStream.WaveFormat, LAMEPreset.ABR_320))
    {
        byte[] bytes = new byte[waveStream.Length];
        waveStream.Position = 0;
        waveStream.Read(bytes, 0, (int)waveStream.Length);
        mpFileWriter.Write(bytes, 0, bytes.Length);
        mpFileWriter.Flush();
    }
    

    If that doesn't work, I guess the LameMP3FileWriter implementation does something wrong with the file handler