2016-12-28 75 views
0

哎每一個機構,我想一個MP3文件解碼爲PCM:mpg123的解碼MP3爲PCM在C++

#include <iostream> 
#include <mpg123.h> 
#include <out123.h> 
using namespace std; 
int main() 
{ 
mpg123_handle *mh; 
unsigned char *buffer; 
size_t buffer_size; 
size_t done; 
int err; 
int channels, encoding; 
long rate; 
buffer_size = mpg123_outblock(mh); 
buffer = (unsigned char*) malloc(buffer_size * sizeof(unsigned char)); 

mpg123_init(); 
mh = mpg123_new(NULL, &err); 

mpg123_open(mh, "/home/abbas/Desktop/nastaran.mp3"); 
// mpg123_getformat(mh, &rate, &channels, &encoding); 



while (mpg123_read(mh, buffer, buffer_size, &done) == MPG123_OK) 
    cout << buffer ; 

free(buffer); 
mpg123_close(mh); 
mpg123_delete(mh); 
mpg123_exit(); 
return 0; 
} 

,但它給這個犯錯

The program has unexpectedly finished. 

錯誤隻字不提的原因,我不知道問題在哪裏?是關於操作系統的一些事情?

cmake的文件:

project(echoprint2) 
cmake_minimum_required(VERSION 2.8) 

aux_source_directory(. SRC_LIST) 
add_executable(${PROJECT_NAME} ${SRC_LIST}) 

add_library(mpg123 SHARED IMPORTED) 
set_target_properties(mpg123 PROPERTIES IMPORTED_LOCATION /usr/local  /lib/libmpg123.so) 
TARGET_LINK_LIBRARIES(echoprint2 mpg123) 
+0

一般來說,這個消息意味着你的程序崩潰了。在調試器下執行它,你應該能夠找到問題。 –

回答

1

我修正了一些錯誤,並得到了待產的一些數值。我把它留給你來檢查產生的波形是否正確。建議使用Excel和Audacity將其可視化並確認波形看起來沒問題。

#include <iostream> 
#include <mpg123.h> 
#include <out123.h> 

int main(){ 
    mpg123_init(); 

    int err; 
    mpg123_handle *mh = mpg123_new(NULL, &err); 
    unsigned char *buffer; 
    size_t buffer_size; 
    size_t done; 

    int channels, encoding; 
    long rate; 
    buffer_size = mpg123_outblock(mh); 
    buffer = (unsigned char*)malloc(buffer_size * sizeof(unsigned char)); 

    mpg123_open(mh, "/home/abbas/Desktop/nastaran.mp3"); 
    mpg123_getformat(mh, &rate, &channels, &encoding); 

    std::ofstream out("res.txt"); 
    unsigned int counter = 0; 

    for (int totalBtyes = 0; mpg123_read(mh, buffer, buffer_size, &done) == MPG123_OK;) { 
     short* tst = reinterpret_cast<short*>(buffer); 
     for (auto i = 0; i < buffer_size/2; i++) { 
      out<< counter + i<<"\t"<< tst[i] << "\n"; 
     } 
     counter += buffer_size/2; 
     totalBtyes += done; 
    } 
    out.close(); 
    free(buffer); 
    mpg123_close(mh); 
    mpg123_delete(mh); 
    mpg123_exit(); 
    return 0; 
} 
+0

謝謝你的作品。但你能解釋爲什麼你使用short *類型的緩衝區,爲什麼你使用我的

+0

哦,我發現了!當sizeof(char)是1時sizeof(short)是2個字節,這就是爲什麼你使用buffer_size/2作爲條件。 –