不能在线程中使用mpg123库

时间:2015-10-26 16:30:44

标签: c++ audio pthreads mp3

我想完成在不同的线程中播放mpg123的mp3歌曲,将trackid作为参数传递,这样我就可以选择合适的歌曲了。我使用的代码是下面的代码。

我有两个问题。有时程序不会创建线程,当它执行时,正确的值被传递和打印,歌曲永远不会播放。

我也尝试将mpg123库与system()一起使用,当正确创建线程时,歌曲也能正常播放。我在线程中的mpg代码有问题吗?谢谢。

编译代码:

g ++ -g -Wall -pthread mpg.cpp -lmpg123 -lao -lpthread -o mpg

#include <ao/ao.h>
#include <mpg123.h>
#include "pthread.h"
#define BITS 8

#include <iostream>
using namespace std;




int playaudio(int  trakid)
{

//works when called here including path
//const char *traklink="/home/pi/downloads/00000050.mp3";
char * traklink="";
int tid=trakid;

if (tid==1){
    cout<<tid<<endl;
    traklink="/home/mixa/karavi.mp3";}
   mpg123_handle *mh;
    unsigned char *buffer;
    size_t buffer_size;
    size_t done;
    int err;

    int driver;
    ao_device *dev;

    ao_sample_format format;
    int channels, encoding;
    long rate;

   /* if(argc < 2)
        exit(0);
*/
    /* initializations */
    ao_initialize();
    driver = ao_default_driver_id();
    mpg123_init();
    mh = mpg123_new(NULL, &err);
    buffer_size = mpg123_outblock(mh);
    buffer = (unsigned char*) malloc(buffer_size * sizeof(unsigned char));

    /* open the file and get the decoding format */
    //mpg123_open(mh,traklink);
    mpg123_open(mh,traklink);
     mpg123_getformat(mh, &rate, &channels, &encoding);

    /* set the output format and open the output device */
   format.bits = mpg123_encsize(encoding) * BITS;
    format.rate = rate;
    format.channels = channels;
    format.byte_format = AO_FMT_NATIVE;
    format.matrix = 0;
    dev = ao_open_live(driver, &format, NULL);

    /* decode and play */
    while (mpg123_read(mh, buffer, buffer_size, &done) == MPG123_OK)
        //ao_play(dev, buffer, done);
        ao_play(dev, (char*)buffer, done);
    /* clean up */
    free(buffer);
    ao_close(dev);
    mpg123_close(mh);
    mpg123_delete(mh);
    mpg123_exit();
    ao_shutdown();
//system("mpg123 -q traklink");


  return 0;
}


void *threading (void *trakid)
{
long tid=(long)trakid;
cout<<"sound plays on:Thread id, "<<tid<<endl;
playaudio(tid);
pthread_exit(NULL);
}

int main()
{
int rc;
long trakid=1;
//const char * trakl="/home/mixa/karavi.mp3";
pthread_t hThread;

rc=pthread_create(&hThread,NULL,threading,(void *)trakid);
cout<<rc<<endl;
//playaudio( trakl);

return 0;
}    

1 个答案:

答案 0 :(得分:0)

在播放完mp3文件之前,您的程序正从main退出。您需要在退出main之前等待。您可以通过添加pthread_join等待线程退出来完成此操作。

rc=pthread_create(&hThread,NULL,threading,(void *)trakid);
cout<<rc<<endl;
// don't exit until thread has finished
pthread_join(hThread, NULL);

或使用信号量或通过调用sleep。