Giter Site home page Giter Site logo

sharpaudio's Introduction

SharpAudio

SharpAudio is a cross-platform, backend-agnostic library to playback sounds in .NET. It achieves that by wrapping the platform specific backends.

Supported backends:

  • XAudio2
  • OpenAL

Build status

Build Status Nuget

Example

SharpAudio provides a low-level interface that wraps audio sources & buffers:

    var engine = AudioEngine.CreateDefault();
    var buffer = engine.CreateBuffer();
    var source = engine.CreateSource();

    // Play a 1s long sound at 440hz
    AudioFormat format;
    format.BitsPerSample = 16;
    format.Channels = 1;
    format.SampleRate = 44100;
    float freq = 440.0f;
    var size = format.SampleRate;
    var samples = new short[size];

    for (int i = 0; i < size; i++)
    {
        samples[i] = (short)(32760 * Math.Sin((2 * Math.PI * freq) / size * i));
    }

    buffer.BufferData(samples, format);

    source.QueueBuffer(buffer);

    source.Play();

A high level interface that can load and play sound files is provided in the SharpAudio.Codec package:

    var engine = AudioEngine.CreateDefault();
    var soundStream = new SoundStream(File.OpenRead("test.mp3"), engine);

    soundStream.Volume = 0.5f;
    soundStream.Play();

The following sound formats are supported at the moment:

  • .wav (PCM & ADPCM)
  • .mp3
  • .ogg (WIP: Vorbis & Opus)

sharpaudio's People

Contributors

charliefoxtwo avatar dependabot[bot] avatar feliwir avatar jeremyvignelles avatar jmacato avatar voldien avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sharpaudio's Issues

Demo volume too loud?

The demo code uses volume 50.0f... that is extremely loud on my speaks and causing crackling. Even a volume on 1.0f is quite loud and occasionally causes crackling. Is the volume meant to be in a range of 0-100 or 0-1?

System.NullReferenceException on Raspberry PI - how to debug?

Hey there,

I tried SharpAudio on Raspberry PI and got an Exception. I already installed openal:

ldconfig -p | grep openal
	libopenal.so.1 (libc6,hard-float) => /lib/arm-linux-gnueabihf/libopenal.so.1

I think, that SharpAudio might fail to load the library for some reason, but unfortunately I have no idea how to debug this...

  • The wav file exists
  • openal is installed
  • libopenal.so.1 exists

Here is the code I used:

var soundFile = "testing.wav";
if (!File.Exists(soundFile))
{
    Console.WriteLine(soundFile + " does not exist");
}
else
{
	var engine = AudioEngine.CreateDefault();
	var soundStream = new SoundStream(File.OpenRead(soundFile), engine);
	soundStream.Play();

	var timer = new Stopwatch();
	timer.Start();
	while (soundStream.IsPlaying && timer.ElapsedMilliseconds < 5000)
	{
		Thread.Sleep(50);
	}
	soundStream.Stop();
}

And the exception:

System.NullReferenceException: Object reference not set to an instance of an object.
   at SharpAudio.BufferChain..ctor(AudioEngine engine)
   at SharpAudio.Codec.SoundSink..ctor(AudioEngine audioEngine, Submixer submixer, ISoundSinkReceiver receiver)
   at SharpAudio.Codec.SoundStream..ctor(Stream stream, AudioEngine engine, Submixer mixer)
   at App.Run(String deviceNode)

Could you please help me out again? :-) Thank you

Changing playback speed

I tried looking at all the properties of AudioEngine and SoundStream, and i cant find a way to speed up/slow down the audio playback live

.net core

does this work on .net core on any os?

MacOS: System.NullReferenceException with the official sample from README.md

Hello,

I just wanted to try out the library on MacOS with the sample Code from the Readme:

            var engine = AudioEngine.CreateDefault();
            var buffer = engine.CreateBuffer();
            var source = engine.CreateSource();

            // Play a 1s long sound at 440hz
            AudioFormat format;
            format.BitsPerSample = 16;
            format.Channels = 1;
            format.SampleRate = 44100;
            float freq = 440.0f;
            var size = format.SampleRate;
            var samples = new short[size];

            for (int i = 0; i < size; i++)
            {
                samples[i] = (short)(32760 * Math.Sin((2 * Math.PI * freq) / size * i));
            }

            buffer.BufferData(samples, format);

            source.QueueBuffer(buffer);

            source.Play();

It failed with and unhandled exception:

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
   at App.Run() in App.cs:line 105
   at Program.<Main>$(String[] args) in Program.cs:line 13

The line, that fails, is:

            var buffer = engine.CreateBuffer();

Environment:

  • MacOS 10.15.7 (Catalina)
  • dotnet --version: 6.0.101

What am I doing wrong?

Null Reference Exception Playing SoundStream

        private bool doEmitSound(PlaySFX req, GameState state, Instant instant)
        {
            if (!allowSFX)
                return true;
            state.Messages.EmitMsg(new ConsoleInput($"Playing {req.Resource}"));
            if (!soundboard.ContainsKey(req.Resource))
                soundboard.Add(req.Resource, new SoundStream(AssetManager.FindFileStream(req.Resource), sfxEngine));
            soundboard[req.Resource].Volume = (currentVolume * req.Volume);//Should be at most 1*1.
            soundboard[req.Resource].Play();
            return true;
        }

This code plays the sound as expected the first time, but fails with a null reference exception when the volume property is modified or the play method is called. the second time regardless of being a new SoundStream or an existing SoundStream.

.NET Standard 2.0 support?

Having switched to Vortice.Windows, are you now able to release a version targeting .NET Standard 2.0 (or any version of .NET Framework)?

Could not find the native OpenAL library on MacOS

I have a problem with AudioEngine.CreateDefault() trying to find the OpenAL library. (I'm using a Mac)
I think a simple enough fix would be to add /System/Library/Frameworks/OpenAL.framework/OpenAL to the library search path like OpenTK.OpenAL does... or maybe you just want to use OpenTK.OpenAL (or some other OpenAL bindings) instead to avoid manually binding OpenAL yourself?
P.S. AudioEngine.CreateDefault() doesn't tell you/warn that it can return null.

Null Reference Exception after disposing and re-initializing object

if (!String.IsNullOrEmpty(_nextSongToPlay))
            {
                if (activeMusic!=null && activeMusic.State== SoundStreamState.Playing)
                {
                    activeMusic.Stop();
                    activeMusic.Dispose();
                }
                activeMusic = new SoundStream(System.IO.File.OpenRead(_nextSongToPlay), musicEngine);
                    System.Threading.Thread.Sleep(100);
                    activeMusic.Volume = currentVolume;
                        activeMusic.Play();
                _nextSongToPlay = null;
            }

It seems that there is some kind of race condition that is triggered by calling the activeMusic.Stop(); method... without putting a System.Threading.Thread.Sleep setting the volume on the activeMusic soundstream causes a null exception to be thrown.

This exception occurs if the activeMusic soundstream is or is not disposed, but only if it was not null before creating the New soundStream

FFmpeg_Initialize() fails on Windows

Trying to read a mp3 file on Windows, the following exception gets raised:

Unable to load DLL 'avutil.56': The specified module could not be found.'

The mp3 gets played on Linux without issues.

Increased audio playback speed while playing an MP3

When attempting to play this MP3 file, the playback speed appears to be much faster (it sounds nearly double) compared to using an audio player. Playing another MP3 worked fine.

To recreate the bug:

var engine = AudioEngine.CreateDefault();
var soundStream = new SoundStream(File.OpenRead("example.mp3"), engine);

soundStream.Volume = 50.0f;
soundStream.Play();

Access violation error

Hello, I've been testing this library with slightly modified code which was provided as example:

var engine = AudioEngine.CreateDefault();
var buffer = engine.CreateBuffer();
var source = engine.CreateSource();

// Play a 1s long sound at 440hz
AudioFormat format;
format.BitsPerSample = 16;
format.Channels = 1;
format.SampleRate = 44100;
float freq = 440.0f;
var size = format.SampleRate;
var samples = new short[size];

for (int i = 0; i < size; i++)
{
    samples[i] = (short)(32760 * Math.Sin((2 * Math.PI * freq) / size * i));
}

buffer.BufferData(samples, format);

for (int i = 0; i < 60; i++)
{
    source.QueueBuffer(buffer);
}

source.Play();

However, after running this code and getting approximately two seconds of playback, the app crashes with code 3221225477 (0xc0000005) 'Access violation'. One time it haven't crashed, but weird noise started to come from the speakers. Do you know what may be causing this issue? Is there maybe some maximum length that the buffer is supposed to have for it to run stably?
Thank you and have a nice day!

High CPU usage

Hi, for me this lib is the best for .Net, but (for me) has an issue.
I don't know the reason, but SharpAudio has an high CPU usage problem.

this is the code:

static void Main(string[] args)
        {
            var  engine = AudioEngine.CreateDefault();
	    string path = "path"; //the song in mp3 file.

            if (engine == null)
            {
                Console.WriteLine("Failed to create an audio backend!");
            }

            if(!File.Exists(path))
            {
            Console.WriteLine("The file does not exist.");
	            return;
            }
            else
            {
            Console.WriteLine("The file exists.");
            }

            var  soundStream = new SoundStream(File.OpenRead(path), engine);
            soundStream.Volume = 10f;
            Console.WriteLine("Loaded Correctly");
            soundStream.Play();
        }

has this CPU usage:
image

for example, MS Edge with 3 open tabs with youtube, uses a little of CPU (~5%)
image

the lib with mp3 file uses the 10% to 16% of CPU, my CPU is an Ryzen 5600X, this is so high. (~1 core )

The lib is like that? or is there a solution?

AVutil.56 not found

Hello, For me this project is amazing, but I receive this error always:

D:\TestProjects\TestSharpAudio>dotnet run
Unhandled exception. System.DllNotFoundException: Unable to load DLL 'avutil.56': The specified module could not be found.
   at FFmpeg.AutoGen.ffmpeg.LoadLibrary(String libraryName)
   at FFmpeg.AutoGen.ffmpeg.<>c__DisplayClass5_0.<.cctor>b__0(String name)
   at FFmpeg.AutoGen.ffmpeg.<>c.<.cctor>b__5_601(UInt64 size)
   at SharpAudio.Codec.FFmpeg.FFmpegDecoder.Ffmpeg_Initialize()
   at SharpAudio.Codec.FFmpeg.FFmpegDecoder..ctor(Stream src)
   at SharpAudio.Codec.SoundStream..ctor(Stream stream, SoundSink sink, Boolean autoDisposeSink)
   at SharpAudio.Codec.SoundStream..ctor(Stream stream, AudioEngine engine, Submixer mixer)
   at SharpAudio.Sample.Program.Main(String[] args) in D:\TestProjects\TestSharpAudio\Program.cs:line 15

this is the code:

        static void Main(string[] args)
        {
            var  engine = AudioEngine.CreateDefault();
            var  soundStream = new SoundStream(File.OpenRead("path"), engine); //in this is throw the error, this says "System.DllNotFoundException: Unable to load DLL 'avutil.56'"
            soundStream.Volume = 50f;
            Console.WriteLine("Loaded Correctly");
            soundStream.Play();
        }

Settongs:

  • Windows 10 20H2
  • Net 5.0

Using high level interface to play audio represented as float[]?

Hello,
is it somehow possible to use the higher-level interface implementation to play back audio represented as float[], with individual samples being in the range of -1 to 1?
I tried, but didn't manage to find a way to create the SoundStream from this kind of data.
Thank you!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.