[2008] Using BASS.DLL to play music and sound effects.
BASS is a very tiny, very powerful audio library that with minimal effort you can use to play WAV, AIFF, MP3, and OGG formatted sound. It is free for use in non-commercial applications. It can play sounds from files or you can pre-load them into memory and trigger them at will, which is perfect for high-speed game sound effects.
To use it with VB.NET though, you just need to define some functions and you're ready to go!
Below is an audio class that shows you how to pre-load two sound samples into memory and trigger them as needed. It will also play .MP3 and .OGG music from a directory (with a random shuffle) on a background thread.
Your project only needs the BASS.DLL file included in it's startup directory to take advantage of BASS. Likewise, there is a .NET wrapper called BASS.NET, but this doesn't have the same licensing as the .DLL and requires a license key to function.
Code:
Public Class Audio
Implements IDisposable
Private booAbortMusic As Boolean
Private t As Threading.Thread
Private Const BASS_POS_BYTE As UInteger = 0
Private Const BASS_DEVICE_DEFAULT As UInteger = 2
'Directory my music and sounds are in.
Private Const MUSICDIR As String = "Music"
Private Const SOUNDDIR As String = "Sound"
Private Declare Function BASS_Init Lib "bass.dll" (ByVal device As Integer, ByVal freq As UInteger, ByVal flags As UInteger, ByVal win As IntPtr, ByVal clsid As UInteger) As Boolean
Private Declare Function BASS_Free Lib "bass.dll" () As Boolean
Private Declare Function BASS_ChannelStop Lib "bass.dll" (ByVal handle As IntPtr) As Boolean
Private Declare Function BASS_ChannelGetLength Lib "bass.dll" (ByVal handle As IntPtr, ByVal mode As Integer) As Integer
Private Declare Function BASS_StreamFree Lib "bass.dll" (ByVal handle As IntPtr) As Boolean
Private Declare Function BASS_ChannelGetPosition Lib "bass.dll" (ByVal handle As IntPtr, ByVal mode As Integer) As Integer
Private Declare Function BASS_ChannelPlay Lib "bass.dll" (ByVal handle As IntPtr, ByVal restart As Boolean) As Boolean
Private Declare Function BASS_SetVolume Lib "bass.dll" (ByVal volume As Single) As Boolean
Private Declare Function BASS_StreamCreateFile Lib "bass.dll" Alias "BASS_StreamCreateFile" (ByVal mem As Boolean, ByVal file As String, ByVal offset As UInteger, ByVal offsethigh As UInteger, ByVal length As UInteger, ByVal lengthhigh As UInteger, ByVal flags As UInteger) As IntPtr
Private Declare Function BASS_SampleLoad Lib "bass.dll" Alias "BASS_SampleLoad" (ByVal mem As Boolean, ByVal file As String, ByVal offset As UInteger, ByVal offsethigh As UInteger, ByVal length As UInteger, ByVal max As UInteger, ByVal flags As UInteger) As IntPtr
Private Declare Function BASS_SampleFree Lib "bass.dll" (ByVal handle As IntPtr) As Boolean
Private Declare Function BASS_SampleGetChannel Lib "bass.dll" (ByVal handle As IntPtr, ByVal onlynew As Boolean) As IntPtr
Private Declare Function BASS_SampleStop Lib "bass.dll" (ByVal handle As IntPtr) As Boolean
Private dSounds As New Dictionary(Of Integer, IntPtr)
Public Sub New()
BASS_Init(-1, 44100, BASS_DEVICE_DEFAULT, IntPtr.Zero, Nothing)
'Preload my sound effects into memory so they can be triggered quickly.
dSounds.Add(1, BASS_SampleLoad(False, String.Format("{0}\{1}\{2}", Application.StartupPath, SOUNDDIR, "Gameover.wav"), 0, 0, 0, 5, 0))
dSounds.Add(2, BASS_SampleLoad(False, String.Format("{0}\{1}\{2}", Application.StartupPath, SOUNDDIR, "LevelUp.wav"), 0, 0, 0, 5, 0))
End Sub
Public Sub PlaySound(ByVal Key As Integer)
'Play a sound effect from memory.
BASS_ChannelPlay(BASS_SampleGetChannel(dSounds(Key), False), False)
End Sub
Public Sub PlayMusic()
'Start up the music.
booAbortMusic = False
t = New Threading.Thread(AddressOf MusicThread)
t.Name = "BackgroundMusic"
t.IsBackground = True
t.Start()
End Sub
Public Sub StopMusic()
'Stop the music.
booAbortMusic = True
If t.IsAlive Then t.Join(1000)
End Sub
Public Sub Dispose() Implements System.IDisposable.Dispose
'Get rid of the Audio object.
For Each d As KeyValuePair(Of Integer, IntPtr) In dSounds
BASS_SampleFree(d.Value)
Next
StopMusic()
BASS_Free()
End Sub
Private Function Shuffle(ByVal strTempList As List(Of String)) As List(Of String)
'Shuffle a list of music randomly.
Dim rand As New Random
Dim strResult As New List(Of String)
Dim i As Integer
For j As Integer = 1 To strTempList.Count
i = rand.Next(0, strTempList.Count)
strResult.Add(strTempList.Item(i))
strTempList.RemoveAt(i)
Next
Return strResult
End Function
Private Sub MusicThread()
'This is the actual routine that's playing the music. I use a background thread to play it.
Dim strPath As String = String.Format("{0}\{1}\", Application.StartupPath, MUSICDIR)
Dim strDirs As New List(Of String)
Dim intLength As Long
Dim stream As IntPtr
strDirs.AddRange(IO.Directory.GetFiles(strPath, "*.mp3"))
strDirs.AddRange(IO.Directory.GetFiles(strPath, "*.ogg"))
strDirs = Shuffle(strDirs)
For i As Integer = 0 To strDirs.Count - 1
stream = BASS_StreamCreateFile(False, strDirs(i), 0, 0, 0, 0, 0)
intLength = BASS_ChannelGetLength(stream, BASS_POS_BYTE)
If booAbortMusic Then Exit For
If stream <> IntPtr.Zero Then
BASS_SetVolume(0.5)
BASS_ChannelPlay(stream, False)
Do Until BASS_ChannelGetPosition(stream, BASS_POS_BYTE) = intLength OrElse booAbortMusic
Threading.Thread.Sleep(1000)
Loop
End If
BASS_StreamFree(stream)
If booAbortMusic Then Exit For
Next
BASS_ChannelStop(stream)
End Sub
End Class
Re: [2008] Using BASS.DLL to play music and sound effects.
Thanks for finding Bass for me jenner but I can't seem to get it to run. I get this: Unable to load DLL 'bass.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
I put it in the bass.net.dll file every where all over my project. I added to the references just like it said in the readme file. But for some reason it can't find it. I even tried it on the samples that the provided. I'm using VB 2008. Here's my code
Every time it gets to the first if statement it crashes and i get the error. Where and how do I add the bass.dll file to my project thanks.
Code:
Imports System
Imports Un4seen.Bass
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' init BASS using the default output device
If Bass.BASS_Init(-1, 44100, BASSInit.BASS_DEVICE_DEFAULT, IntPtr.Zero, Nothing) Then
' create a stream channel from a file
Dim stream As Integer = Bass.BASS_StreamCreateFile("c:\test.mp3", 0L, 0L, BASSFlag.BASS_DEFAULT)
If stream <> 0 Then
' play the stream channel
Bass.BASS_ChannelPlay(stream, False)
Else
' error creating the stream
'Console.WriteLine("Stream error: {0}", Bass.BASS_ErrorGetCode())
End If
' wait for a key
'Console.WriteLine("Press any key to exit")
'Console.ReadKey(False)
' free the stream
'Bass.BASS_StreamFree(stream)
' free BASS
'Bass.BASS_Free()
End If
End Sub
End Class
Re: [2008] Using BASS.DLL to play music and sound effects.
which dl from the website is that one? the only one I could find is the bass.net.dll download but that came with the whole thing. I downloaded the Bass.Net 2.4.3 it doesn't have a bass.dll just the bass.net.dll file.
Re: [2008] Using BASS.DLL to play music and sound effects.
You want THIS link, it's at the VERY top of their BASS page. You'll see a Windows and Mac download link. No winder you couldn't get it to work because you need that to even get BASS.NET to work as well.
I'll warn you, unlicensed, BASS.NET will have a splash/popup when you start your program. That's why in my example I just call the library directly.
Re: [2008] Using BASS.DLL to play music and sound effects.
Jenner,
Looks cool!
One issue I'm having though...I'm a REAL noob. I added the "bass.dll" to my solution from the link you provided above...now I don't know how/where to add your code.
Re: [2008] Using BASS.DLL to play music and sound effects.
It's a Class object. Step-by-step:
Drag Bass.dll into your project directory.
Start Visual Studio.
Go to the Solution Explorer on the right hand side, you should see Bass.dll there. Right-click it and "Include in Project".
In the properties below, "Copy to Output Directory" = "Copy if newer"
In the Solution Explorer, click on your project. Right click and "Add->Class".
In the popup, change the name to "Audio.vb".
You should now have an "Audio.vb" object in your Solution Explorer, double-click it to open it.
Copy-paste my code to it, overwriting anything in there.
Ok, now it's in your project. In order to use it, you need to modify my code a little bit, since it's only an example, typically, in the areas where you're telling it where to find the sounds and music. My example assumes, in the directory where your program is being run from, you have a "Music" directory which has MP3s and/or OGG files in it, and a "Sound" directory with at least two WAV files in it called "Gameover.wav" and "LevelUp.wav".
If you're following my example to the letter, then to use the class, from your main form or wherever you want to use it:
Code:
Dim aud As New Audio
aud.PlaySound(1) 'To play the first sound FX
aud.PlayMusic() 'To start music playback
Re: [2008] Using BASS.DLL to play music and sound effects.
Jenner,
Walked through your step by step instructions (thanks again for taking the time!)...
Got this error when trying to run:
"Error while trying to run project: could not load file or assembly 'bass' or one of its dependencies. The module was expected to contain an assembly manifest."
I'm in VS2008, by the way, and assume that is making a difference in the outcome.
Re: [2008] Using BASS.DLL to play music and sound effects.
Here's a mega-quick audio project I whipped up to show you how to use it. Not included is the bass.dll library. You MUST drop this into the directory. I made a file called "PUT BASS.DLL HERE.txt" where you need to drop it.
I did include 2 sound samples (wavs) and an mp3 (just a 16hz to 20khz test-sweep pattern) so you can see how that works. The only change I made to my class I posted above is I added a While loop onto the music routine so it'll loop continuously until you hit stop.
Re: [2008] Using BASS.DLL to play music and sound effects.
A reference to 'E:\Stuff\bass.dll' could not be added. Please make sure that the file is accessible, and that it is a valid assembly or COM component.
OK... now that's a creepy problem
Somebody got a solution...!?
The example on using BASS.DLL was very helpfull. Thank you.
Could you possibly post an example on how to add additional filetype support like flac. I noticed that extra filetypes have additional dlls but I can't figure out how to use them.
Re: [2008] Using BASS.DLL to play music and sound effects.
I'm afraid I've never really explored how to use the additional format libraries. Taking a peek at BASSFLAC.DLL though, the VB example they provide (even though it's VB6) looks like it has everything you need to add the additional functions it gives you to the class I provided.
For example, look at the part of my example that loads a music file and plays it. See the part in there: BASS_StreamCreateFile()? You'd simple replace that with BASS_FLAC_StreamCreateFile() if it was a FLAC file.
Re: [2008] Using BASS.DLL to play music and sound effects.
Originally Posted by Jenner
For example, look at the part of my example that loads a music file and plays it. See the part in there: BASS_StreamCreateFile()? You'd simple replace that with BASS_FLAC_StreamCreateFile() if it was a FLAC file.
Thanks for help. It seems to work so that one must make these calls before the initialization:
Re: [2008] Using BASS.DLL to play music and sound effects.
thanks for the tutorial, i very interested about that.
And i try to be use that, but when i run in vb 2008, it doesn't work normally and show the dialog box:
"An error occurred creating the form. See Exception.InnerException for details. The error is: Unable to load DLL 'bass.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)"
can you help me, please.