source: trunk/src/sdl/sdl_audio.cc @ 329

Last change on this file since 329 was 329, checked in by epyon, 11 years ago
  • audio now based on handles
File size: 2.1 KB
Line 
1// Copyright (C) 2012-2014 ChaosForge Ltd
2// http://chaosforge.org/
3//
4// This file is part of NV Libraries.
5// For conditions of distribution and use, see copyright notice in nv.hh
6
7#include "nv/sdl/sdl_audio.hh"
8
9#include "nv/lib/sdl.hh"
10#include "nv/lib/sdl_mixer.hh"
11#include "nv/core/logging.hh"
12
13using namespace nv;
14
15sdl::audio::audio()
16{
17        nv::load_sdl_library();
18        nv::load_sdl_mixer_library();
19
20        if ( SDL_Init( SDL_INIT_AUDIO ) == -1 )
21        {
22                NV_LOG( LOG_CRITICAL, "SDL_AUDIO failed to load -- " << SDL_GetError() );
23                return;
24        }
25
26        if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 1024 ) == -1 )
27        {
28                NV_LOG( LOG_CRITICAL, "SDL_mixer failed to load -- " << Mix_GetError() );
29                return;
30        }
31}
32
33
34nv::channel sdl::audio::play_sound( sound a_sound )
35{
36        sound_info* info = m_sounds.get( a_sound );
37        if ( info )
38        {
39                if ( Mix_PlayChannel(-1, (Mix_Chunk*)( info->sdl_sound), 0) == -1 )
40                {
41                        NV_LOG( LOG_WARNING, "SDL_mixer failed to play -- " << Mix_GetError() );
42                }
43        }
44        return channel();
45}
46
47nv::sound nv::sdl::audio::load_sound( const std::string& a_path )
48{
49        // TODO: this is a really wierd error - if we remove this check, all hell gets loose
50        if ( Mix_LoadWAV_RW == nullptr || SDL_RWFromFile == nullptr )
51        {
52                NV_LOG( LOG_ERROR, "SDL_mixer not loaded!" );
53        }
54        Mix_Chunk *sample = Mix_LoadWAV_RW(SDL_RWFromFile(a_path.c_str(), "rb"), 1);
55        if ( sample == nullptr )
56        {
57                NV_LOG( LOG_ERROR, "SDL_mixer failed to load sample '" << a_path << "' -- " << Mix_GetError() );
58                return sound();
59        }
60        sound result = m_sounds.create();
61        sound_info* info = m_sounds.get( result );
62        info->sdl_sound = sample;
63        return result;
64}
65
66void nv::sdl::audio::update()
67{
68        // no-op
69}
70
71nv::sdl::audio::~audio()
72{
73        while ( m_sounds.size() > 0 )
74                release( m_sounds.get_handle(0) );
75        Mix_CloseAudio();
76        // TODO: should we do it here?
77        SDL_Quit();
78}
79
80void nv::sdl::audio::release( sound a_sound )
81{
82        sound_info* info = m_sounds.get( a_sound );
83        if ( info )
84        {
85                Mix_FreeChunk( (Mix_Chunk*)info->sdl_sound );
86                m_sounds.destroy( a_sound );
87        }
88}
89
Note: See TracBrowser for help on using the repository browser.