3

我目前正在使用 gtk+ 和 c++ 代码构建一个非常简单的音乐播放器,但现在我无法弄清楚如何使用 C++ 代码打开和播放音频文件。

#include <gtk/gtk.h>
// simple music player to practice gtk and c++//

int main(int argc, char* argv[])
{
gtk_init(&argc,&argv);

GtkWidget *window;
GtkWidget *playButton;
GtkWidget *fileButton;
GtkWidget *frame;
GtkWidget *Dialog;


window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER);
gtk_window_set_default_size(GTK_WINDOW(window), 400, 400);

frame = gtk_fixed_new();
gtk_container_add(GTK_CONTAINER(window), frame);

playButton = gtk_button_new_with_label("Play");
gtk_widget_set_size_request(playButton,80,40);
gtk_fixed_put(GTK_FIXED(frame),playButton,40,330);

fileButton = gtk_button_new_with_label("Open");
gtk_widget_set_size_request(fileButton,80,40);
gtk_fixed_put(GTK_FIXED(frame),fileButton,40,260);

gtk_widget_show_all(window);
gtk_main();

return 0;
}

如您所见,我创建了打开按钮来选择您的文件,并且我知道对话框代码;

GtkWidget *dialog;

dialog = gtk_file_chooser_dialog_new ("OpenFile",parent_window,GTK_FILE_CHOOSER_ACTION_OPEN,GTK_STOCK_CANCEL,GTK_RESPONSE_CANCEL,GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL);

if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT)
  {
    char *filename;

    filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
    open_file (filename);
   g_free (filename);
 }

gtk_widget_destroy (dialog);

但我的问题是我不知道如何放置代码,我很可能应该创建一个函数并在单击打开按钮时为该函数设置回调。正确的?然后第二个问题出现,无论我多么努力搜索,我似乎都找不到如何播放音频文件,提前非常感谢!

4

1 回答 1

2

如果您不介意使用外部库Allegro可以非常轻松地播放各种格式的音频文件。以下是如何播放 .wav 音频文件的示例。

#include <stdio.h>
#include <allegro5/allegro.h>
#include <allegro5/allegro_audio.h>
#include <allegro5/allegro_acodec.h>

int main(int argc, char **argv){

   ALLEGRO_DISPLAY *display = NULL;
   ALLEGRO_SAMPLE *sample=NULL;

   if(!al_init()){
      fprintf(stderr, "failed to initialize allegro!\n");
      return -1;
   }

   if(!al_install_audio()){
      fprintf(stderr, "failed to initialize audio!\n");
      return -1;
   }

   if(!al_init_acodec_addon()){
      fprintf(stderr, "failed to initialize audio codecs!\n");
      return -1;
   }

   if (!al_reserve_samples(1)){
      fprintf(stderr, "failed to reserve samples!\n");
      return -1;
   }

   sample = al_load_sample( "footstep.wav" );

   if (!sample){
      printf( "Audio clip sample not loaded!\n" ); 
      return -1;
   }

   display = al_create_display(640, 480);

   if(!display){
      fprintf(stderr, "failed to create display!\n");
      return -1;
   }

   /* Loop the sample until the display closes. */
   al_play_sample(sample, 1.0, 0.0,1.0,ALLEGRO_PLAYMODE_LOOP,NULL);

   al_rest(10.0);

   al_destroy_display(display);
   al_destroy_sample(sample);
   return 0;
}
于 2013-07-22T20:33:23.050 回答