2013-10-05 42 views
0

我們已經定義了我們的基本代碼如下。當我們按下相應的按鍵時,代碼片段會播放音樂。現在的問題是file1更短,file2稍長。我們需要將兩者混合並以這種方式播放它們,以延長file1的持續時間以匹配file2。如何通過SDL做?使用SDL混音器的比賽持續時間

Mix_Chunk *file1 = NULL; 
Mix_Chunk *file2 = NULL; 

file1 = Mix_LoadWAV("file1.wav"); 
    file2 = Mix_LoadWAV("file2.wav"); 

    while(quit == false) 
    { 
     //While there's events to handle 
     while(SDL_PollEvent(&event)) 
     { 
      //If a key was pressed 
      if(event.type == SDL_KEYDOWN) 
      { 
       //If 1 was pressed 
       if(event.key.keysym.sym == SDLK_1) 
       { 
        //Play the scratch effect 
        if(Mix_PlayChannel(-1, file1, 0) == -1) 
        { 
         return 1; 
        } 
       } 
       //If 2 was pressed 
       else if(event.key.keysym.sym == SDLK_2) 
       { 
        //Play the high hit effect 
        if(Mix_PlayChannel(-1, file2, 0) == -1) 
        { 
         return 1; 
        } 
       }    

      } 
      //If the user has Xed out the window 
      if(event.type == SDL_QUIT) 
      { 
       //Quit the program 
       quit = true; 
      } 
     } 
+0

@任何想法如何去關於他們我是新來的 – user2711681

+0

你正在玩他們的頻道。它們應該重疊。 – this

+0

如何在多個通道上播放它們並對文件1進行伸縮以匹配file2的長度 – user2711681

回答

0

你將不得不做一些上採樣或下采樣。在你的情況下,你可能需要對file1進行上採樣以延長它。這是如何:

// This function add samples from the original audio according to the value of "rate". 
// Since the sampling rate remains the same, effectively it will cause the audio to playback slower. 
void Play_UpSample (int channel, Mix_Chunk *sample, int loop, int rate) 
{ 
    int m, n; 
    Mix_Chunk *newsample = new Mix_Chunk; 
    int original_length = sample->alen; 
    int length = original_length * rate;  

    newsample->allocated = sample->allocated; 
    newsample->abuf = NULL; 
    newsample->alen = length; 
    newsample->volume = sample->volume; 
    Uint8 *data1 = new Uint8[length]; 
    Uint8 *start = sample->abuf; 
    Uint8 *start1 = data1; 

    int size = Get_Format(); 

    if (size == 32) { 
     Uint32 sam; 

     for (m=1; m<=original_length; m+=4) { 
      sam = *((Uint32 *)start); 
      for (n=1; n<=rate; n++) { 
       *((Uint32 *)start1) = sam; 
       start1+=4; 
      } 
      start+=4; 
     } 
    } 
    else if (size == 16) { 
     Uint16 sam; 
     for (m=1; m<=original_length; m+=2) { 
      sam = *((Uint16 *)start); 
      for (n=1; n<=rate; n++) { 
       *((Uint16 *)start1) = sam; 
       start1+=2; 
      } 
      start+=2; 
     } 

    } 
    else if (size == 8) { 
     Uint8 sam; 
     for (m=1; m<=original_length; m+=4) { 
      sam = *start; 
      for (n=1; n<=rate; n++) { 
       *start1 = sam; 
       start1++; 
      } 
      start++; 
     } 


    } 
    newsample->abuf = data1; 

    Mix_PlayChannel(channel, newsample, loop); 
} 
相關問題