2014-01-23 4 views
-2

Game dev class. Попытка понять, что я сделал неправильно здесь. Я добавил что-то не так, или у меня это не в том месте. моей целью было добавить музыку.Нужно это для воспроизведения музыки

#include "allegro5/allegro.h" 
#include <allegro5/allegro_image.h> 
#include <allegro5/allegro_font.h> 
#include <allegro5/allegro_ttf.h> 
#include <allegro5/allegro_native_dialog.h> 
#include <stdio.h> 
#include <string> 
#include <allegro5\allegro_audio.h> 
#include <allegro5\allegro_acodec.h> 


#define FPS 60 
#define SCREEN_WIDTH 800 
#define SCREEN_HEIGHT 600 
#define BLACK al_map_rgb(0, 0, 0) 
#define WHITE al_map_rgb(255, 255, 255) 

//Prototypes 
bool initializeAllegro(); 

//Essential Allegro pointers 
ALLEGRO_DISPLAY *display = NULL; 
ALLEGRO_EVENT_QUEUE *eventQueue = NULL; 
ALLEGRO_TIMER *timer = NULL; 
ALLEGRO_FONT *arial14; 

int main() 
{ 
    ALLEGRO_BITMAP *backgroundImage; //Bitmap for the background image(star field) 
    int backgroundImageWidth = 0, backgroundImageHeight = 0; 

    bool redrawRequired = true; 
    //Using std:string for name, so length is not a factor 
    std::string userName = ""; 
    std::string prompt1 = "Enter your Player's name below"; 
    std::string prompt2 = "(Letters & digits only. Backspace to erase.)"; 
    std::string prompt3 = "Press Enter to accept..."; 
    std::string prompt4 = "Press Escape to exit..."; 
    char keyToAdd = ' '; 
    bool enteringUserName = true; 
    bool quit = false; 

    //Initialize allegro, etc 
    if (!initializeAllegro()) return -1; 

    //load the arial font 
    arial14 = al_load_font("arial-mt-black.ttf", 14, 0); 
    if (!arial14) 
    { 
     return -3; 
    } 
    //test running music 
    al_init_acodec_addon(); 

    ALLEGRO_SAMPLE *song = al_load_sample("hideandseek.wav"); 
    ALLEGRO_SAMPLE_INSTANCE *songInstance = al_create_sample_instance(song); 
    al_set_sample_instance_playmode(songInstance, ALLEGRO_PLAYMODE_LOOP); 
    al_attach_sample_instance_to_mixer(songInstance, al_get_default_mixer()); 

    //Load the background picture 
    if (!(backgroundImage = al_load_bitmap("starbackground.bmp"))) 
    { 
     return -5; 
    } 

    //Get dimensions of the background image 
    backgroundImageWidth = al_get_bitmap_width(backgroundImage); 
    backgroundImageHeight = al_get_bitmap_height(backgroundImage); 

    //Set the back buffer as the drawing bitmap for the display 
    al_set_target_bitmap(al_get_backbuffer(display)); 

    //Initialize the event queue 
    eventQueue = al_create_event_queue(); 
    if (!eventQueue) 
    { 
     al_destroy_display(display); 
     al_destroy_timer(timer); 
     return -1; 
    } 

    //Register events as arriving from these sources: display, timer, keyboard 
    al_register_event_source(eventQueue, al_get_display_event_source(display)); 
    al_register_event_source(eventQueue, al_get_timer_event_source(timer)); 
    al_register_event_source(eventQueue, al_get_keyboard_event_source()); 

    al_flip_display(); 

    //play song 
    al_play_sample_instance(songInstance); 

    //Start up the timer. Don't do this until just before the game is to start! 
    al_start_timer(timer); 

    //This would be a loop solely for entering the user's name, not starting the game 
    //Allegro keycodes are laid out as follows. (Full set of key codes is included in keycodes.h) 
    //Key codes for capital letters are 1 - 26 for A - Z 
    //Digit values are 27 - 36 for the top digits (0 - 9), and 37 - 46 for the keypad 
    while (!quit) 
    { 
     ALLEGRO_EVENT evt; 
     //Wait for one of the allegro-defined events 
     al_wait_for_event(eventQueue, &evt); 

     //An event was generated. Check for all possible event types 
     switch (evt.type) 
     { 
      case ALLEGRO_EVENT_KEY_CHAR: 
       if (evt.keyboard.keycode >= 1 && evt.keyboard.keycode <= 26) //It's a capital letter 
       { 
        //Convert to ASCII capital 
        keyToAdd = *al_keycode_to_name(evt.keyboard.keycode); 
        userName += keyToAdd; 
       } 
       else if (evt.keyboard.keycode >= 27 && evt.keyboard.keycode <= 36) 
       { 
        //Convert to digit 
        keyToAdd = evt.keyboard.keycode + 21; 
        userName += keyToAdd; 
       } 
       //Handle digits on keypad 
       else if (evt.keyboard.keycode >= 37 && evt.keyboard.keycode <= 46) 
       { 
        //Convert to digit 
        keyToAdd = evt.keyboard.keycode + 11; 
        userName += keyToAdd; 
       } 
       else //Handle a few other keys 
       { 
        switch(evt.keyboard.keycode) 
        { 
         case ALLEGRO_KEY_BACKSPACE: 
          if (userName.length() > 0) 
           userName = userName.substr(0, userName.length() - 1); 
          break; 

         //Enter key stops username entry 
         case ALLEGRO_KEY_ENTER: 
         case ALLEGRO_KEY_PAD_ENTER: 
          enteringUserName = false; 
          break; 
         case ALLEGRO_KEY_ESCAPE: 
          quit = true; 
          break; 
        } 
       } 
       break; 

      case ALLEGRO_EVENT_DISPLAY_CLOSE: 
       quit = true; 
       break; 

      case ALLEGRO_EVENT_TIMER: 
       redrawRequired = true; 
       break; 

     }//END switch evt.type 

     //Rerender the entire scene 
     if (redrawRequired && al_is_event_queue_empty(eventQueue)) 
     { 
      redrawRequired = false; 

      al_clear_to_color(BLACK); //Just in case 

      //Draw background 
      al_draw_scaled_bitmap(backgroundImage, 0, 0, backgroundImageWidth, backgroundImageHeight, 
       0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0); 

      //Prompt for name to be entered 
      al_draw_textf (arial14, WHITE, 0, 30, 0, "%s", prompt1.c_str()); 
      al_draw_textf (arial14, WHITE, 0, 50, 0, "%s", prompt2.c_str()); 
      if (userName.length() > 0) 
      { 
       if (enteringUserName) 
       { 
        al_draw_textf (arial14, WHITE, 0, 70, 0, "%s", userName.c_str()); 
        al_draw_textf (arial14, WHITE, 0, 90, 0, "%s", prompt3.c_str()); 
       } 
       else 
       { 
        al_draw_textf (arial14, WHITE, 0, 70, 0, "You entered your name as-->%s", userName.c_str()); 
       } 
      } 

      al_draw_textf(arial14, WHITE, 0, 400, 0, "%s", prompt4.c_str()); 

      al_flip_display(); 
     }//END rendering the screen 

    }//END input Loop 

    //Release all dynamically allocated memory 
    al_destroy_bitmap(backgroundImage); 
    al_destroy_font(arial14); 
    al_destroy_timer(timer); 
    al_destroy_display(display); 
    al_destroy_event_queue(eventQueue); 
    //destroy songs 
    al_destroy_sample(song); 
    al_destroy_sample_instance(songInstance); 

    return 0; 
}//END main 

//Take care of Allegro initialization tasks 
//Return false if any fail. 
bool initializeAllegro() 
{ 
    bool success = true; 

    //Init basic environment 
    if (!al_init()) 
    { 
     al_show_native_message_box(NULL, "ERROR", "Allegro failed to initialize!", NULL, NULL, NULL); 
     success = false; 
    } 

    //Initialize keyboard input 
    if (!al_install_keyboard()) 
    { 
     al_show_native_message_box(NULL, "ERROR", "Keyboard failed to initialize!", NULL, NULL, NULL); 
     success = false; 
    } 

    //Initialize timer 
    timer = al_create_timer(1.0/FPS); 
    if (!timer) 
    { 
     al_show_native_message_box(NULL, "ERROR", "Timer failed to initialize!", NULL, NULL, NULL); 
     success = false; 
    } 

    //Initialize display 
    display = al_create_display(SCREEN_WIDTH, SCREEN_HEIGHT); 
    if (!display) 
    { 
     al_show_native_message_box(NULL, "ERROR", "Display failed to initialize!", NULL, NULL, NULL); 
     success = false; 
    } 

    //Initialize the image mechanism 
    if (!al_init_image_addon()) 
    { 
     al_show_native_message_box(NULL, "ERROR", "Image addon failed to initialize!", NULL, NULL, NULL); 
     success = false; 
    } 

    al_init_font_addon(); 
    al_init_ttf_addon(); 

    return success; 
}//END initializeAllegro 

Любой wav-файл должен работать. я получаю сообщение об ошибке -

первого шанса исключение в 0x0F196486 (аллегро-5.0.10-монолитно-мкр-debug.dll) в Input Пользователь Project.exe: 0xC0000005: нарушение прав доступа чтения места 0x00000000 , Необработанное исключение в 0x0F196486 (allegro-5.0.10-monolith-md-debug.dll) в User Входной файл Project.exe: 0xC0000005: Место чтения нарушения доступа 0x00000000.

Программа '[9596] Пользовательский вход Project.exe' вышел с кодом 0 (0x0).

+2

Можете ли вы попробовать выполнить код с помощью отладчика, чтобы увидеть, в какую строку он разбивается? Похоже, вы пытаетесь получить доступ к указателю NULL. – AndyG

+0

http://meta.stackexchange.com/a/216019/179793 – jogojapan

+0

Почему я получил - на все мои вопросы? –

ответ

3

Я упомянул пошагово вещей с помощью отладчика в мой комментарий, но код запах здесь заключается в следующем:

ALLEGRO_SAMPLE *song = al_load_sample("hideandseek.wav"); 
ALLEGRO_SAMPLE_INSTANCE *songInstance = al_create_sample_instance(song); 

Вы должны Определенно быть проверка (song == NULL) перед вызовом al_create_sample_instance()

Если ваш путь к файлу .WAV неверен или если загрузка по какой-либо другой причине не выполняется, то al_load_sample() вернет NULL, и вы не должны пытаться ничего делать с помощью song

+0

Я тоже попробую. Я нашел основную проблему, я не поместил ее в нее. al_install_audio(); \t al_init_acodec_addon(); \t al_reserve_samples (1); –