繁体   English   中英

无法在线程中使用mpg123库

[英]Cannot use mpg123 library in thread

我想完成将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;
}    

在完成播放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);

或带有信号量或通过调用睡眠。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM