1. 程式人生 > >使用libvlc播放音樂,實時獲取位置、播放狀態、時長,播放httpURL

使用libvlc播放音樂,實時獲取位置、播放狀態、時長,播放httpURL

#include <iostream>
#include <unistd.h>

#include "vlc/vlc.h"  
#include "libvlc.h"
#include "libvlc_media_player.h"
#include "libvlc_media.h"

#include "log_c.h"
#include "VlcMusicPlayer.h"

#define url_temp "/share/music/1KHz-stero.wav"
#define http_url  "http://101.132.74.49:8080/bcch.wav"

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

	VlcMusicPlayer   VlcMusicPlayerHandle;
	int i =0;
	for(i = 0; i < argc ;i++ )
	{
		LOG_ERROR(("%d argv %s",i, argv[i]));

	}

	if(std::string(argv[1]) == std::string("http"))
	{

		std::string  url(http_url);
		LOG_ERROR(("=%s", url.c_str()));
		VlcMusicPlayerHandle.openUrl( url);
	}
	else
	{
		std::string  url(url_temp);
		LOG_ERROR(("=%s", url.c_str()));
		VlcMusicPlayerHandle.openFile( url);
	}
	

	while(1)
	{
		sleep(0xff);
	}
	
	return  0;
}




VlcMusicPlayer.h

/******************************
 * Qt player using libVLC     *
 * By protonux                *
 *                            *
 * Under WTFPL                *
 ******************************/

#ifndef VlcMusicPlayer_H
#define VlcMusicPlayer_H

#include <iostream>

#include "vlc/vlc.h"  
#include "libvlc.h"
#include "libvlc_media_player.h"
#include "libvlc_media.h"

class VlcMusicPlayer 
{
        public:
               VlcMusicPlayer();
               virtual ~VlcMusicPlayer();

        public:
			   int init();
               void  openFile(const std::string & file_string);
			   void   openUrl(const std::string & url);
               void play();
               void stop();
               void mute();
               int  changeVolume(int);
               void changePosition(int);
               void updateInterface();
			   void timer(int ms);
			   void StartTimer();
			   void StopTimer();
			   #if 0
			   void music_register();
			   void music_unregister();
			   void   OnEndReached( const struct libvlc_event_t *p_event, void *p_data );
               void   OnPositionChanged( const struct libvlc_event_t *p_event, void *p_data );
			   	#endif
        private:
               libvlc_instance_t 		*vlcInstance;
               libvlc_media_player_t 	*vlcPlayer;
			   libvlc_media_t 			*vlcMedia ;
			   libvlc_event_manager_t   *vlc_evt_man;
			   long long                m_s64Duration;
			   int                      m_nCurPos;
			   bool                     m_isMuteFlag;
			   int 						m_cur_vol;
			   libvlc_state_t  			m_emPlayState;

			   
};


#endif


VlcMusicPlayer.cpp

#include <unistd.h>
#include <thread>

#include "VlcMusicPlayer.h"
#include "log_c.h"

static int  g_sStopTimerFlag = 0; 

#define    TimerInternal     (300)

VlcMusicPlayer::VlcMusicPlayer()
{
    vlcPlayer = NULL;
	vlcInstance = NULL;
 	vlcMedia = NULL ;
	vlc_evt_man = NULL;
	m_s64Duration = -1;
	m_nCurPos = -1;
	m_isMuteFlag = false;

	m_cur_vol = 0;
	m_emPlayState = libvlc_NothingSpecial;
    int ret = init();
	if(0 != ret)
	{
		 LOG_ERROR((" VlcMusicPlayer  init   error!"));
		 return ;
	}
}

VlcMusicPlayer::~VlcMusicPlayer() 
{
    /* Release libVLC instance on quit */
	LOG_ERROR((" "));
	stop();
    if (vlcInstance)
    {
		libvlc_release(vlcInstance);
    }
}

int VlcMusicPlayer::init()
{
	static bool   sInitFlag = false;

	if(sInitFlag == true)
	{
		LOG_ERROR((" libVLC player  do not  repeat init libVLC"));
		return 0;
	}
	
     /* Initialize libVLC */
    vlcInstance = libvlc_new(0, NULL);

    /* Complain in case of broken installation */
    if (vlcInstance == NULL) 
	{
        LOG_ERROR((" libVLC player  Could not init libVLC"));
        return -1;
    }

	
	sInitFlag= true ;

	LOG_ERROR((" libVLC player  init libVLC success "));
	return 0;
    /* Interface initialization */
}

void VlcMusicPlayer::openFile(const std::string & file_string)
{

    /* The basic file-select box */
    //url  to utf-8 url
    
    /* Stop if something is playing */
    if (vlcPlayer && libvlc_media_player_is_playing(vlcPlayer))
    {
    	LOG_DEBUG(("libvlc_media_player_is_playing  ,to stop "));
        stop();
    }
	
    /* Create a new Media */
    vlcMedia = libvlc_media_new_path(vlcInstance, file_string.c_str());
    if (!vlcMedia)
    {
    	LOG_ERROR(("libvlc_media_new_path  error "));
        return;
    }
    /* Create a new libvlc player */
    vlcPlayer = libvlc_media_player_new_from_media (vlcMedia);
	if(NULL == vlcPlayer)
	{
		LOG_ERROR(("libvlc_media_player_new_from_media  error "));
		return;
	}
    /* Release the media */
    //libvlc_media_release(vlcMedia);

    /* And start playback */
    libvlc_media_player_play (vlcPlayer);

	StartTimer();
	
    /* Update playback button */
    //playBut->setText("Pause");
}

void VlcMusicPlayer::openUrl(const std::string & url)
{
	
		/* The basic file-select box */
		//url  to utf-8 url
		
		/* Stop if something is playing */
		if (vlcPlayer && libvlc_media_player_is_playing(vlcPlayer))
		{
			LOG_DEBUG(("libvlc_media_player_is_playing	,to stop "));
			stop();
		}
		
		/* Create a new Media */
		vlcMedia = libvlc_media_new_location(vlcInstance, url.c_str());
		if (!vlcMedia)
		{
			LOG_ERROR(("libvlc_media_new_location  error "));
			return;
		}
		/* Create a new libvlc player */
		vlcPlayer = libvlc_media_player_new_from_media (vlcMedia);
		if(NULL == vlcPlayer)
		{
			LOG_ERROR(("libvlc_media_player_new_from_media	error "));
			return;
		}
		/* Release the media */
		//libvlc_media_release(vlcMedia);
	
		/* And start playback */;
		libvlc_media_player_play (vlcPlayer);

		StartTimer();
		/* Update playback button */
		//playBut->setText("Pause");
}

void VlcMusicPlayer::play() {
    if (!vlcPlayer)
    {
    	LOG_ERROR(("vlcPlayer  is  NULL "));
        return;
    }
	
    if (libvlc_media_player_is_playing(vlcPlayer))
    {
        /* Pause */
		LOG_DEBUG(("NEXT  libvlc_media_player_pause()"));
        libvlc_media_player_pause(vlcPlayer);
       // playBut->setText("Play");
    }
    else
    {
        /* Play again */
		LOG_DEBUG(("NEXT  libvlc_media_player_play()"));
        libvlc_media_player_play(vlcPlayer);
       ///playBut->setText("Pause");
    }
}

int VlcMusicPlayer::changeVolume(int vol) { /* Called on volume slider change */

    if (vlcPlayer)
    {
    	int ret = 0;
		LOG_DEBUG(("NEXT  libvlc_audio_set_volume()  vol = %d", vol));
		ret =  libvlc_audio_set_volume (vlcPlayer,vol);

		m_cur_vol = vol;
		return ret;
		
    }
	
    return 0;
}

void VlcMusicPlayer::changePosition(int pos) { /* Called on position slider change */

    if (vlcPlayer)
    {
    	LOG_DEBUG(("NEXT  libvlc_media_player_set_position()  pos = %d", pos));
    	libvlc_media_player_set_position(vlcPlayer, (float)pos/1000.0);
    }
}

void VlcMusicPlayer::updateInterface() //timer
{ //Update interface and check if song is finished

    if (NULL !=vlcPlayer)
    {
    	/* update the timeline */
	    float pos = libvlc_media_player_get_position(vlcPlayer); //pos  is 0.01~0.99 1.0
		m_nCurPos = (int)(pos*1000.0);
	    /* Stop the media */
		libvlc_state_t state = libvlc_media_player_get_state(vlcPlayer);
		m_emPlayState = state;//libvlc_state_t  m_emPlayState
		LOG_DEBUG(("state{%d} m_nCurPos = %d",state, m_nCurPos));
	    if (state == libvlc_Ended)
	    {
	    	this->stop();
	    }
    }

	if(NULL != vlcMedia)
	{
		long long s64Duration = libvlc_media_get_duration( vlcMedia);	
		if(-1 != s64Duration)  //s64Duration/1000 s
		{
			m_s64Duration = s64Duration;

			long long min = s64Duration/1000/60;
			long long sec = s64Duration/1000%60;
			LOG_DEBUG(("m_s64Duration{%lld}  %lld:%lld",m_s64Duration , min,sec));
		}	
	}
	
}


void  VlcMusicPlayer::timer(int ms)
{
	while(1)
	{
		if(g_sStopTimerFlag == 0)
		{
			LOG_DEBUG(("break"));
			break;
		}
		
		updateInterface();

		usleep(1000*ms);// ms
	}
}

void VlcMusicPlayer::StartTimer()
{
	g_sStopTimerFlag = 1;
	LOG_DEBUG(("  "));

	std::thread   t(&VlcMusicPlayer::timer, this , TimerInternal);
	t.detach();
}

void VlcMusicPlayer::StopTimer()
{
	g_sStopTimerFlag = 0;
	LOG_DEBUG(("  "));
}

void VlcMusicPlayer::stop() {

	LOG_DEBUG(("  "));
	StopTimer();
	if(vlcMedia)
	{
		/* Release the media */
		libvlc_media_release(vlcMedia);
		vlcMedia = NULL;
	}
	
    if(vlcPlayer) {
        /* stop the media player */
        libvlc_media_player_stop(vlcPlayer);

        /* release the media player */
        libvlc_media_player_release(vlcPlayer);

        /* Reset application values */
        vlcPlayer = NULL;
		m_emPlayState = libvlc_NothingSpecial;
		m_nCurPos = 0;
       // slider->setValue(0);
        //playBut->setText("Play");
    }
}

void VlcMusicPlayer::mute() {
    if(vlcPlayer) {
        if(m_isMuteFlag == true) { //if already muted...

                this->changeVolume(80);
				m_cur_vol = 80;
				m_isMuteFlag = false;
                //volumeSlider->setValue(80);

        } else { //else mute volume

				m_isMuteFlag = true;
				m_cur_vol = 0;
                this->changeVolume(0);
                //volumeSlider->setValue(0);

        }
    }
}

#if 0
void  VlcMusicPlayer::music_register()
{
#if 0
libvlc_event_manager_t *
libvlc_media_player_event_manager( libvlc_media_player_t *p_mi )
{
    return &p_mi->event_manager;
}
typedef void ( *libvlc_callback_t )( const struct libvlc_event_t *p_event, void *p_data );
libvlc_event_attach(vlc_evt_man, libvlc_MediaPlayerEndReached, ::OnEndReached_VLC, NULL);

#endif
	if(NULL == vlcPlayer)
	{
		LOG_ERROR(("vlcPlayer  is  NULL "));
		return ;
	}
	
	vlc_evt_man = libvlc_media_player_event_manager(vlcPlayer);
    libvlc_event_attach(vlc_evt_man, libvlc_MediaPlayerEndReached,
		(libvlc_callback_t) (&VlcMusicPlayer::OnEndReached), NULL);
	
    libvlc_event_attach(vlc_evt_man, libvlc_MediaPlayerPositionChanged, 
		(libvlc_callback_t)(&VlcMusicPlayer::OnPositionChanged), NULL);

	return ;
}

void  VlcMusicPlayer::music_unregister()
{

}

void VlcMusicPlayer::OnEndReached( const struct libvlc_event_t *p_event, void *p_data )
{
	LOG_ERROR((" "));
	this->stop();
}

void VlcMusicPlayer:: OnPositionChanged( const struct libvlc_event_t *p_event, void *p_data )
{
	if(NULL == vlcPlayer)
	{
		LOG_ERROR(("vlcPlayer  is  NULL "));
		return ;
	}
	float factor = libvlc_media_player_get_position(vlcPlayer);
	LOG_ERROR((" factor [%.2f] ",factor));
	
}

#endif



makefile

CXX = g++
CFLAGS = -Wall -g -std=c++11 -pthread
PWD_OUT := /share/demo_vlc
PWD_SRC := /share/demo_vlc
CICLUDES_PWD := -I /usr/include/vlc -I /usr/include/
CSO_PWD := /usr/lib
libname1 := -lvlc


OBJS := $(PWD_OUT)/vlc_demo.o
OBJS += $(PWD_OUT)/VlcMusicPlayer.o


SRCS := $(PWD_SRC)/vlc_demo.cpp
SRCS += $(PWD_SRC)/VlcMusicPlayer.cpp




TARGET = demo_vlc_app
$(TARGET):$(OBJS)
$(CXX) $(CFLAGS) -o $(TARGET) $(OBJS) -L$(CSO_PWD) $(libname1) $(CICLUDES_PWD)
@echo "=======finish========="
$(PWD_OUT)/%.o:%.cpp
$(CXX) $(CFLAGS) -c $(SRCS) $(CICLUDES_PWD)


clean:
rm $(OBJS)  $(TARGET) -rf
@echo "=============clean ok========"