Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing sound byte[] in C#

I realize that you can use SoundPlayer to play a sound in C#; however, I want to be able to play a sound with the OS-default sound player using this method from a sound represented in a byte array. Is this possible?

like image 421
Mani5556 Avatar asked May 29 '11 16:05

Mani5556


4 Answers

The SoundPlayer constructor accepts a Stream to play. You can get a Stream from a byte[] by creating a MemoryStream.

like image 77
SoftMemes Avatar answered Oct 24 '22 00:10

SoftMemes


Opening any file with an application, e.g. media player, requires a file.

Thus you need to save your byte array into file in some format, e.g. WAV, and open it:

byte[] bytes = ...
string name = Path.ChangeExtension(Path.GetRandomFileName(), ".wav");
string path = Path.Combine(Path.GetTempPath(), name);
File.WriteAllBytes(path, bytes);
Process.Start(path);

This code will open user default media player, the same as you clicked on it in Windows Explorer.

like image 30
abatishchev Avatar answered Oct 24 '22 00:10

abatishchev


abatishchev has a good answer, but you don't need to save the bytes to a file and then play the file. you can write those bytes to a MemoryStream and then play the MemoryStream as this method does:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;

public static void PlayBeep(UInt16 frequency, int msDuration, UInt16 volume = 16383)
{
    var mStrm = new MemoryStream();
    BinaryWriter writer = new BinaryWriter(mStrm);

    const double TAU = 2 * Math.PI;
    int formatChunkSize = 16;
    int headerSize = 8;
    short formatType = 1;
    short tracks = 1;
    int samplesPerSecond = 44100;
    short bitsPerSample = 16;
    short frameSize = (short)(tracks * ((bitsPerSample + 7) / 8));
    int bytesPerSecond = samplesPerSecond * frameSize;
    int waveSize = 4;
    int samples = (int)((decimal)samplesPerSecond * msDuration / 1000);
    int dataChunkSize = samples * frameSize;
    int fileSize = waveSize + headerSize + formatChunkSize + headerSize + dataChunkSize;
    // var encoding = new System.Text.UTF8Encoding();
    writer.Write(0x46464952); // = encoding.GetBytes("RIFF")
    writer.Write(fileSize);
    writer.Write(0x45564157); // = encoding.GetBytes("WAVE")
    writer.Write(0x20746D66); // = encoding.GetBytes("fmt ")
    writer.Write(formatChunkSize);
    writer.Write(formatType);
    writer.Write(tracks);
    writer.Write(samplesPerSecond);
    writer.Write(bytesPerSecond);
    writer.Write(frameSize);
    writer.Write(bitsPerSample);
    writer.Write(0x61746164); // = encoding.GetBytes("data")
    writer.Write(dataChunkSize);
    {
        double theta = frequency * TAU / (double)samplesPerSecond;
        // 'volume' is UInt16 with range 0 thru Uint16.MaxValue ( = 65 535)
        // we need 'amp' to have the range of 0 thru Int16.MaxValue ( = 32 767)
        double amp = volume >> 2; // so we simply set amp = volume / 2
        for (int step = 0; step < samples; step++)
        {
            short s = (short)(amp * Math.Sin(theta * (double)step));
            writer.Write(s);
        }
    }

    mStrm.Seek(0, SeekOrigin.Begin);
    new System.Media.SoundPlayer(mStrm).Play();
    writer.Close();
    mStrm.Close();
} // public static void PlayBeep(UInt16 frequency, int msDuration, UInt16 volume = 16383)

For your question, you don't need most the code in this method that creates the WAV-formatted byte stream, but you can use the trick at the end of the method to avoid having to save the bytes to a file.

like image 4
Shawn Kovac Avatar answered Oct 24 '22 01:10

Shawn Kovac


Try from How to play from an array

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();
}
like image 1
Aleks Avatar answered Oct 24 '22 00:10

Aleks