qt qmediaplayerr对象play后没有声音,什么情况

博客访问: 2363454
博文数量: 946
博客积分: 12961
博客等级: 上将
技术积分: 10378
注册时间:
IT168企业级官微
微信号:IT168qiye
系统架构师大会
微信号:SACC2013
分类: Android平台
在Android中,音频、视频等多媒体元素的加入,使得应用程序的用户体验更好。可以说,现在的手机,已经远远不只作为通信工具,更成为娱乐、办公的必备产品。
Android提供了简单的音频API。一般大家使用的是MediaPlayer播放音频,这也是最常见的一种播放声音的工具。这种工具在互联网上有大量的实例,因此在此只做简单的介绍。
对播放行为的控制是三个大家非常熟悉的方法:start()、stop()和pause()。
通过static MediaPlayer create(Context, Uri)这个方法,可以获得一个新创建的MediaPlayer对象。
在播放过程中,有几个可以监听播放过程的监听器,如:
n setOnCompletionListener(MediaPlayer.OnCompletionListener listener),监听音频播放结束;
n setOnErrorListener(MediaPlayer.OnErrorListener listener),监听播放过程中的错误事件;
n setOnPreparedListener(MediaPlayer.OnPreparedListener listener),当prepare()被调用时触发。
然而,使用MediaPlayer播放时,也有一些问题。我们知道MediaPlayer在创建和销毁时都会耗费大量的系统资源,且创建和销毁的时间相对较长。此外,如果我们需要在同一时刻播放很多声音,MediaPlayer是不支持的。
因此,我们需要一个更加轻量级的声音播放工具。
Android提供了另外一种,叫做SoundPool,它适合播放那些需要反复播放,但时间较短的音效。它支持同时播放多种声音,这些声音在系统开始时会加载到列表中,按照这些声音的id,我们可以调用这些音效。
下面我们进入一个实例看看SoundPool到底是怎么工作的。
例如,现在在一个五子棋游戏中,我们需要在棋子落盘的时候播放一段声音。我们可以利用SoundPool,因为它时间很短,而且需要反复播放,并且我们不希望声音占用太大资源。
先看看代码:
private SoundPool soundPool;
soundPool= newSoundPool(10,AudioManager.STREAM_SYSTEM,5);
soundPool.load(this,R.raw.collide,1);
soundPool.play(1,1, 1, 0, 0, 1);
代码非常简单,第一行是声明了一个SoundPool对象,这个一般是作为类的成员属性出现的。第二行将soundPool实例化,第一个参数为soundPool可以支持的声音数量,这决定了Android为其开设多大的缓冲区,第二个参数为声音类型,在这里标识为系统声音,除此之外还有AudioManager.STREAM_RING以及AudioManager.STREAM_MUSIC等,系统会根据不同的声音为其标志不同的优先级和缓冲区,最后参数为声音品质,品质越高,声音效果越好,但耗费更多的系统资源。
第三行,系统为soundPool加载声音,第一个参数为上下文参数,第二个参数为声音的id,一般我们将声音信息保存在res的raw文件夹下,如下图所示。
第三个参数为声音的优先级,当多个声音冲突而无法同时播放时,系统会优先播放优先级高的。
第四行就是播放了,第一个参数为id,id即为放入到soundPool中的顺序,比如现在collide.wav是第一个,因此它的id就是1。第二个和第三个参数为左右声道的音量控制。第四个参数为优先级,由于只有这一个声音,因此优先级在这里并不重要。第五个参数为是否循环播放,0为不循环,-1为循环。最后一个参数为播放比率,从0.5到2,一般为1,表示正常播放。
=====================================================================
android开发播放声音文件
MediaPlayer mediaPlayer01;
mediaPlayer01 = MediaPlayer.create(YouActivity.this, R.raw.xxxx);
mediaPlayer01.start();
网上有很多介绍mp播放声音文件的几种方式就是:
1.用R.raw.x来播放raw目录下的文件,
2.用setDataSource("/sdcard/s.mp4"),但是没有说如果想用setDataSource()这样的方式播放raw目录下的文件(setDataSource("/raw/s.mp4")这样不行)。
Himi& 原创, 欢迎转载,转载请在明显处注明! 谢谢。
原文地址:
游戏开发中,通过资料和书籍了解到在有两种播放音频形式可以用在我们的游戏开发中,第一个:MediaPlayer 类 ;第二个:SoundPool 类!
PS:当然还有一个JetPlayer 但是 播放的文件格式比较麻烦,所以这里抛开不解释,有兴趣的可以去自己研究下、呵呵;
运行效果图:
MediaPlayer 和:SoundPool 类!那么他们之间的利弊各是什么呢?或者说,我们游戏开发到底用哪一个更佳呢?
答案就是:两者都必须要!!!分析利弊与各自的用途后,等各位童鞋熟习每个播放形式实现之后我会详细道来!
&下面仍然是先上代码:(先看代码 然后我讲解两个播放形式的利弊关系和各个用途以及其中解释代码中的几个备注!)
package com.&&&
import java.util.HashM&&&
import android.content.C&&&
import android.graphics.C&&&
import android.graphics.C&&&
import android.graphics.P&&&
import android.media.AudioM&&&
import android.media.MediaP&&&
import android.media.SoundP&&&
import android.view.KeyE&&&
import android.view.MotionE&&&
import android.view.SurfaceH&&&
import android.view.SurfaceV&&&
import android.view.SurfaceHolder.C&&&
public class MySurfaceView extends SurfaceView implements Callback, Runnable {&&&
&&& private T&&&
&&& private SurfaceH&&&
&&& private C&&&
&&& private MediaP&&&
&&& private P&&&
&&& private boolean ON =&&&
&&& private int currentVol, maxV&&&
&&& private AudioM&&&&
&&& private HashMap soundPoolM//备注1&&&
&&& private int loadId;&&&
&&& private SoundPool soundP&&&
&&& public MySurfaceView(Context context) {&&&
&&&&&&& super(context);&&&
// 获取音频服务然后强转成一个音频管理器,后面方便用来控制音量大小用&&&
&&&&&&& am = (AudioManager) MainActivity.instance&&&
&&&&&&&&&&&&&&& .getSystemService(Context.AUDIO_SERVICE);&&&
&&&&&&& maxVol = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);&&&
&&&&&&& // 获取最大音量值(15最大! .不是100!)&&&
&&&&&&& sfh = this.getHolder();&&&
&&&&&&& sfh.addCallback(this);&&&
&&&&&&& th = new Thread(this);&&&
&&&&&&& this.setKeepScreenOn(true);&&&
&&&&&&& setFocusable(true);&&&
&&&&&&& paint = new Paint();&&&
&&&&&&& paint.setAntiAlias(true);&&&
&&&&&&& //MediaPlayer的初始化&&&
&&&&&&& player = MediaPlayer.create(context, R.raw.himi);&&&&
&&&&&&& player.setLooping(true);//设置循环播放&&&
&&&&&&& //SoundPool的初始化&&&
&&&&&&& soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);&&&
&&&&&&& soundPoolMap = new HashMap();&&&
&&&&&&& soundPoolMap.put(1, soundPool.load(MainActivity.content,&&&
&&&&&&&&&&&&&&& R.raw.himi_ogg, 1));&&&
&&&&&&& loadId = soundPool.load(context, R.raw.himi_ogg, 1);&&&
//load()方法的最后一个参数他标识优先考虑的声音。目前没有任何效果。使用了也只是对未来的兼容性价值。&&&
&&& public void surfaceCreated(SurfaceHolder holder) {&&&
&&&&&&& /*&
&&&&&&&& * Android OS中,如果你去按手机上的调节音量的按钮,会分两种情况,&
&&&&&&&& * 一种是调整手机本身的铃声音量,一种是调整游戏,软件,音乐播放的音量&
&&&&&&&& * 当我们在游戏中的时候 ,总是想调整游戏的音量而不是手机的铃声音量,&
&&&&&&&& * 可是烦人的问题又来了,我在开发中发现,只有游戏中有声音在播放的时候&
&&&&&&&& * ,你才能去调整游戏的音量,否则就是手机的音量,有没有办法让手机只要是&
&&&&&&&& * 在运行游戏的状态就只调整游戏的音量呢?试试下面这段代码吧!&
&&&&&&&& */&&&
&&&&&&& MainActivity.instance.setVolumeControlStream(AudioManager.STREAM_MUSIC);&&&
&&&&&&& // 设定调整音量为媒体音量,当暂停播放的时候调整音量就不会再默认调整铃声音量了,娃哈哈&&&
&&&&&&&&&&&
&&&&&&& player.start();&&&
&&&&&&& th.start();&&&
&&& public void draw() {&&&
&&&&&&& canvas = sfh.lockCanvas();&&&
&&&&&&& canvas.drawColor(Color.WHITE);&&&
&&&&&&& paint.setColor(Color.RED);&&&
&&&&&&& canvas.drawText("当前音量: " + currentVol, 100, 40, paint);&&&
&&&&&&& canvas.drawText("当前播放的时间" + player.getCurrentPosition() + "毫秒", 100,&&&
&&&&&&&&&&&&&&& 70, paint);&&&
&&&&&&& canvas.drawText("方向键中间按钮切换 暂停/开始", 100, 100, paint);&&&
&&&&&&& canvas.drawText("方向键←键快退5秒 ", 100, 130, paint);&&&
&&&&&&& canvas.drawText("方向键→键快进5秒 ", 100, 160, paint);&&&
&&&&&&& canvas.drawText("方向键↑键增加音量 ", 100, 190, paint);&&&
&&&&&&& canvas.drawText("方向键↓键减小音量", 100, 220, paint);&&&
&&&&&&& sfh.unlockCanvasAndPost(canvas);&&&
&&& private void logic() {&&&
&&&&&&& currentVol = am.getStreamVolume(AudioManager.STREAM_MUSIC);// 不断获取当前的音量值&&&
&&& @Override&&&
&&& public boolean onKeyDown(int key, KeyEvent event) {&&&
&&&&&&& if (key == KeyEvent.KEYCODE_DPAD_CENTER) {&&&
&&&&&&&&&&& ON = !ON;&&&
&&&&&&&&&&& if (ON == false)&&&
&&&&&&&&&&&&&&& player.pause();&&&
&&&&&&&&&&& else&&&
&&&&&&&&&&&&&&& player.start();&&&&
&&&&&&& } else if (key == KeyEvent.KEYCODE_DPAD_UP) {// 按键这里本应该是RIGHT,但是因为当前是横屏模式,以下雷同&&&
&&&&&&&&&&& player.seekTo(player.getCurrentPosition() + 5000);&&&
&&&&&&& } else if (key == KeyEvent.KEYCODE_DPAD_DOWN) {&&&
&&&&&&&&&&& if (player.getCurrentPosition() < 5000) {&&&
&&&&&&&&&&&&&&& player.seekTo(0);&&&
&&&&&&&&&&& } else {&&&
&&&&&&&&&&&&&&& player.seekTo(player.getCurrentPosition() - 5000);&&&
&&&&&&&&&&& }&&&
&&&&&&& } else if (key == KeyEvent.KEYCODE_DPAD_LEFT) {&&&
&&&&&&&&&&& currentVol += 1;&&&
&&&&&&&&&&& if (currentVol > maxVol) {&&&
&&&&&&&&&&&&&&& currentVol = 100;&&&
&&&&&&&&&&& }&&&
&&&&&&&&&&& am.setStreamVolume(AudioManager.STREAM_MUSIC, currentVol,// 备注2&&&
&&&&&&&&&&&&&&&&&&& AudioManager.FLAG_PLAY_SOUND);&&&
&&&&&&& } else if (key == KeyEvent.KEYCODE_DPAD_RIGHT) {&&&
&&&&&&&&&&& currentVol -= 1;&&&
&&&&&&&&&&& if (currentVol <= 0) {&&&
&&&&&&&&&&&&&&& currentVol = 0;&&&
&&&&&&&&&&& }&&&
&&&&&&&&&&& am.setStreamVolume(AudioManager.STREAM_MUSIC, currentVol,&&&
&&&&&&&&&&&&&&&&&&& AudioManager.FLAG_PLAY_SOUND);&&&
&&&&&&& }&&&
&&&&&&& soundPool.play(loadId, currentVol, currentVol, 1, 0, 1f);// 备注3&&&
//&&&&& soundPool.play(soundPoolMap.get(1), currentVol, currentVol, 1, 0, 1f);//备注4&&&
//&&&&& soundPool.pause(1);//暂停SoundPool的声音&&&&
&&&&&&& return super.onKeyDown(key, event);&&&
&&& @Override&&&
&&& public boolean onTouchEvent(MotionEvent event) {&&&
&&&&&&&&&&
&&& public void run() {&&&
&&&&&&& // TODO Auto-generated method stub&&&
&&&&&&& while (true) {&&&
&&&&&&&&&&& draw();&&&
&&&&&&&&&&& logic();&&&
&&&&&&&&&&& try {&&&
&&&&&&&&&&&&&&& Thread.sleep(100);&&&
&&&&&&&&&&& } catch (Exception ex) {&&&
&&&&&&&&&&& }&&&
&&&&&&& }&&&
&&& public void surfaceChanged(SurfaceHolder holder, int format, int width,&&&
&&&&&&&&&&& int height) {&&&&&
&&& public void surfaceDestroyed(SurfaceHolder holder) {&&&&&
一、 MediaPlayer 播放音频的实现步骤:
1. 调用MediaPlayer.create(context, R.raw.himi); 利用MediaPlayer类调用create方法并且传入通过id索引的资源音频文件,得到实例;
2. 得到的实例就可以调用 MediaPlayer.star();
简单吧、其实MediaPlayer还有几个构造方法,大家有兴趣可以去尝试和实现,这里主要是简单的向大家介绍基本的,毕竟简单实用最好!
& 二、 SoundPlayer 播放音频的实现步骤:
1.&& new出一个实例 ;&& new SoundPool(4, AudioManager.STREAM_MUSIC, 100);第一个参数是允许有多少个声音流同时播放,第2个参数是声音类型,第三个参数是声音的品质;
2.loadId = soundPool.load(context, R.raw.himi_ogg, 1);
3. 使用实例调用play方法传入对应的音频文件id即可!
下面讲下两个播放形式的利弊:
&&&&&&& 使用MediaPlayer来播放音频文件存在一些不足:
例如:资源占用量较高、延迟时间较长、不支持多个音频同时播放等。
这些缺点决定了MediaPlayer在某些场合的使用情况不会很理想,例如在对时间精准度要求相对较高的游戏开发中。
最开始我使用的也是普通的MediaPlayer的方式,但这个方法不适合用于游戏开发,因为游戏里面同时播放多个音效是常有的事,用过MediaPlayer的朋友都该知道,它是不支持实时播放多个声音的,会出现或多或少的延迟,而且这个延迟是无法让人忍受的,尤其是在快速连续播放声音(比如连续猛点按钮)时,会非常明显,长的时候会出现3~5秒的延迟,【使用MediaPlayer.seekTo() 这个方法来解决此问题】;
&&&&&&& 相对于使用SoundPool存在的一些问题:
1. SoundPool最大只能申请1M的内存空间,这就意味着我们只能使用一些很短的声音片段,而不是用它来播放歌曲或者游戏背景音乐(背景音乐可以考虑使用JetPlayer来播放)。
2. SoundPool提供了pause和stop方法,但这些方法建议最好不要轻易使用,因为有些时候它们可能会使你的程序莫名其妙的终止。还有些朋友反映它们不会立即中止播放声音,而是把缓冲区里的数据播放完才会停下来,也许会多播放一秒钟。
3. 音频格式建议使用OGG格式。使用WAV格式的音频文件存放游戏音效,经过反复测试,在音效播放间隔较短的情况下会出现异常关闭的情况(有说法是SoundPool目前只对16bit的WAV文件有较好的支持)。后来将文件转成OGG格式,问题得到了解决。
4.在使用SoundPool播放音频的时候,如果在初始化中就调用播放函数进行播放音乐那么根本没有声音,不是因为没有执行,而是SoundPool需要一准备时间!囧。当然这个准备时间也很短,不会影响使用,只是程序一运行就播放会没有声音罢了,所以我把SoundPool播放写在了按键中处理了、备注4的地方
大概看完了利弊解释,那么来看我的代码备注的地方:
&这里我定义了一个 HashMap ,这个是哈希表,如果大家不是很了解这个类,那建议百度 google学习下,它与Hashtable很常用的,它俩的主要区别是: HashMap&& 不同步、空键值、效率高;& Hashtable&& 同步、非空键值、效率略低 ;而在J2ME中不支持HashMap ,因为me中不支持空键值,所以在me中只能使用hashtable、咳咳、言归正传,我这里使用hashmap主要是为了存入多个音频的ID,播放的时候可以同时播放多个音频。
上面也介绍了,SoundPool可以支持多个音频同时播放,而且SoundPool在播放的时候调用的这个方法(备注3)soundPool.play(loadId, currentVol, currentVol, 1, 0, 1f); 第一个参数指的就是之前的loadId !是通过 soundPool.load(context, R.raw.himi_ogg, 1);方法取出来的,
那么除此之外还要注意一点的就是定义hashmap的时候一定要定义成这种形式HashMap hm = new Hash,声明此哈希表就是一个key和volue值都是Integer的哈希表! 为什么要这么做,因为如果你只是简单的定义成 HashMap hm =new HashMap(),那么当你在播放的时候,也就是备注4方法这里的第一个id参数使用Hashmap.get()这个方法的时候总会出现错误的提示!
《SoundPool最大只能申请1M的内存空间,这就意味着我们只能使用一些很短的声音片段》为什么只能使用一些很短的声音呢?
大家还是看备注4方法的第一个参数,这里要求传入的Id类型是个int值,那么这个int其实对应的是通过load()方法返回的音频id,而且这个id会因音频文件的大小而变大变小,那么一旦我们的音频文件超过int最大值,那么就会报内存错误的异常。所以为什么用SoundPool只能播放一些简短的音频这就是其原因了。当然os 里为什么这么定义 我也无从查证和说明。
备注4 :此方法中参数的解释
第一个参数是我通过SoundPool.load()方法返回的音频对应id,第二个第三个参数表示左右声道大小,第四个参数是优先级,第五个参数是循环次数,最后一个是播放速率(1.0 =正常播放,范围是0.5至2.0)
&这里是通过媒体服务得到一个音频管理器,从而来对音量大小进行调整。这里要强调一下,调整音频是用这个音频管理器调用setStreamVolume()的方式去调整,而不是MediaPlayer.setVolue(int LeftVolume,int RightVolume);这个方法的两个参数也是调正左右声道而不是调节声音大小。
&& 好了,对此我们对游戏开发中到底需要用什么来做进行了分析,总结就是SoundPool适合做特效声,其实播放背景音乐我感觉还是用MediaPlayer比较好,当然啦,用什么都看大家喜好和选择啦!下面附上项目下载地址:(项目10+MB因为含有res音频文件)
有人问& 怎么才知道一首歌曲播放完了,那么这里给说下:
PlaybackCompleted状态:文件正常播放完毕,而又没有设置循环播放的话就进入该状态,并会触发OnCompletionListener的onCompletion()方法。此时可以调用start()方法重新从头播放文件,也可以stop()停止MediaPlayer,或者也可以seekTo()来重新定位播放位置。
注意:1、 别忘记绑定操作! mp.setOnCompletionListener(this);
2、如果你设置了循环播放& mp.setLooping(true); 的话,那么永远都不会监听到播放完成的状态!!!!这里一定要注意!
==============================================================================
android SoundPool 的使用
Android里的SoundPool类是 android.media 包里提供的一个用来播放声音文件的类,可以支持同时播放多个声音文件,可以控制每个文件的循环次数。基本上要遵守下面的步骤:&
1 &实现&&&SoundPool.OnLoadCompleteListener&接口的 onLoadComplete函数
2& New一个SoundPool 的实例 sndPool,构造函数的第一个参数指定最多同时播放的文件个数
3 &设定&&sndPool的 onLoadCompleteListener 回调函数
4& sndPool&.load&一个音频文件,也称为一个流
5& 在&&onLoadComplete函数里判断成功与否,一般在这里发一个消息让activity来调用 sndPool.play 这个流
6 重复4和5,知道你把所有想播放的流都play起来了
可能遇到的问题点:
1& 音频文件不能太大,否则会造成AudioCache的Heap size overflow
2& 一定要收到&onLoadComplete回调之后再 play
3 要在程序的onDestroy里调用 sndPool.release(),否则的话会第二次打开这个程序,不出声音。
4 SoundPool.OnLoadCompleteListener.( soundPool, int sampleId, int status) 的第二个参数sampleId 和 SoundPool.load 返回的参数是同一 个东西。
5&下面所附的代码里还碰到一个问题,开始的时候没有在pause等id后面加100,老是出错,应该是和android内部的定义有冲突。
package com.android.testSoundP
import android.app.A
import android.os.B
import android.os.M
import android.view.V
import android.widget.TextV
import android.widget.B
import android.util.L
import android.media.AudioM
import android.media.SoundP
import android.os.H
public class TestSoundPoolActivity extends Activity implements View.OnClickListener,
&&&&&&&&&&&&&&&&SoundPool.OnLoadCompleteListener& {
&static String TAG="TestSoundPoolActivity" ;
&SoundPool sndP
&int[] StreamID =new int[10] ;
&int StreamNum = 0;
&int StreamNumPause = 0& ;
&int[] rid = new int[]{R.raw.iremembershort1,R.raw.in_call_alarm,R.raw.down,R.raw.down,R.raw.down,R.raw.down,
&&&R.raw.down,R.raw.down,R.raw.down,R.raw.down} ;&
&private static final int SOUND_LOAD_OK = 1;
&private final Handler mHandler = new MyHandler() ;
&&& /** Called when the activity is first created. */
&&& @Override
&&& public void onCreate(Bundle savedInstanceState) {
&&&&&&& super.onCreate(savedInstanceState);
&&&&&&& setContentView(R.layout.main);
&&&&&&& tv = (TextView)findViewById(R.id.textvbb100) ;
&&&&&&& tv.setText("1234567");
&&&&&&& Button b1 = (Button)findViewById(R.id.play100) ;
&&&&&&& b1.setOnClickListener(this);&&&&&&&
&&&&&&& b1 = (Button)findViewById(R.id.more100) ;
&&&&&&& b1.setOnClickListener(this);
&&&&&&& b1 = (Button)findViewById(R.id.pause100) ;
&&&&&&& b1.setOnClickListener(this);
&&&&&&& sndPool = new SoundPool(16, AudioManager.STREAM_MUSIC,0 ) ;
&&&&&&& sndPool.setOnLoadCompleteListener(this);
&&& public void onDestroy()
&&& &sndPool.release() ;
&&& &super.onDestroy();
&&& private class MyHandler extends Handler {
&&& &public void handleMessage(Message msg){
&&& &&switch( msg.what){
&&& &&case SOUND_LOAD_OK:&&& &&&
&&& &&&StreamID[StreamNum] = sndPool.play( msg.arg1, (float)0.8,(float)0.8, 16, 10, (float)1.0) ;
&&& &&&StreamNum ++ ;
&&& public void onLoadComplete(SoundPool soundPool, int sampleId, int status)& {
&&& &Message msg = mHandler.obtainMessage(SOUND_LOAD_OK); ;
&&& &msg.arg1 = sampleI&&& &
&&& &mHandler.sendMessage(msg);
&&& public void onClick(View v) {
&&& &int id = v.getId() ;
&&& &switch ( id )&{&&
&&& &&case R.id.play100:&&
&&& &&&tv.setText("play");
&&& &&&Log.v(TAG , "play main");
&&& &&&if( sndPool != null )&&& &&&&
&&& &&&&sndid = sndPool.load( this , rid[StreamNum] , 1 ) ;&&& &&&&
&&& &&case R.id.more100:
&&& &&&tv.setText("more");
&&& &&&sndPool.load( this , rid[StreamNum] , 1 ) ;
&&& &&&Log.v(TAG , "more");
&&& &&case R.id.pause100:
&&& &&&tv.setText("pause");
&&& &&&if( StreamNumPause< StreamNum )&{
&&& &&&&sndPool.pause(StreamID[StreamNumPause]) ;
&&& &&&&StreamNumPause ++ ;
&&& &&&Log.v(TAG,"pause");
&&& &}&&& &
可以在下载整个代码
阅读(2016) | 评论(0) | 转发(0) |
相关热门文章
给主人留下些什么吧!~~
请登录后评论。QMediaPlayer Class | Qt Multimedia 5.7
QMediaPlayer
QMediaPlayer Class
class allows the playing of a media source.
Header: #include &QMediaPlayer&
qmake: QT += multimedia Inherits:
Public Types
{ NoError, ResourceError, FormatError, NetworkError, AccessDeniedError, ServiceMissingError }
{ LowLatency, StreamPlayback, VideoSurface }
{ UnknownMediaStatus, NoMedia, LoadingMedia, LoadedMedia, ..., InvalidMedia }
{ StoppedState, PlayingState, PausedState }
Properties
: const bool
: QAudio::Role
: const int
: const QMediaContent
: const qint64
: const QString
: QMediaContent
: const MediaStatus
: QMediaPlaylist *
: const bool
: const State
: const bool
1 property inherited from
1 property inherited from
Public Functions
(QObject *parent = Q_NULLPTR, Flags flags = Flags())
QAudio::Role () const
int () const
QMediaContent () const
QNetworkConfiguration () const
qint64 () const
Error () const
QString () const
bool () const
bool () const
bool () const
bool () const
QMediaContent () const
MediaStatus () const
const QIODevice *() const
qreal () const
QMediaPlaylist *() const
qint64 () const
void (QAudio::Role audioRole)
void (QVideoWidget *output)
void (QGraphicsVideoItem *output)
void (QAbstractVideoSurface *surface)
State () const
QList&QAudio::Role& () const
int () const
Reimplemented Public Functions
virtual QMultimedia::AvailabilityStatus () const
10 public functions inherited from
31 public functions inherited from
Public Slots
void (const QMediaContent &media, QIODevice *stream = Q_NULLPTR)
void (bool muted)
void (const QList&QNetworkConfiguration& &configurations)
void (qreal rate)
void (QMediaPlaylist *playlist)
void (qint64 position)
void (int volume)
1 public slot inherited from
void (bool available)
void (QAudio::Role role)
void (int percentFilled)
void (const QMediaContent &media)
void (qint64 duration)
void (QMediaPlayer::Error error)
void (const QMediaContent &media)
void (QMediaPlayer::MediaStatus status)
void (bool muted)
void (const QNetworkConfiguration &configuration)
void (qreal rate)
void (qint64 position)
void (bool seekable)
void (QMediaPlayer::State state)
void (bool videoAvailable)
void (int volume)
6 signals inherited from
2 signals inherited from
Static Public Members
QMultimedia::SupportEstimate (const QString &mimeType, const QStringList &codecs = QStringList(), Flags flags = Flags())
11 static public members inherited from
Additional Inherited Members
2 protected functions inherited from
9 protected functions inherited from
Detailed Description
class allows the playing of a media source.
class is a high level media playback class. It can be used to playback such content as songs, movies and internet radio. The content to playback is specified as a
object, which can be thought of as a main or canonical URL with additional information attached. When provided with a
playback may be able to commence.
player = new ;
connect(player, SIGNAL(positionChanged()), this, SLOT(positionChanged()));
player-&setMedia(::fromLocalFile(&/Users/me/Music/coolsong.mp3&));
player-&setVolume(50);
player-&play();
can be used with
for video rendering and
for accessing playlist functionality.
playlist = new ;
playlist-&addMedia((&/movie1.mp4&));
playlist-&addMedia((&/movie2.mp4&));
playlist-&addMedia((&/movie3.mp4&));
playlist-&setCurrentIndex(1);
player = new ;
player-&setPlaylist(playlist);
videoWidget = new ;
player-&setVideoOutput(videoWidget);
videoWidget-&show();
player-&play();
is a , you can use several of the
functions for things like:
Accessing the currently playing media's metadata (() and )
Checking to see if the media playback service is currently available (())
See also , , , and .
Member Type Documentation
enum QMediaPlayer::Error
Defines a media player error condition.
ConstantValueDescription
QMediaPlayer::NoError0No error has occurred.
QMediaPlayer::ResourceError1A media resource couldn't be resolved.
QMediaPlayer::FormatError2The format of a media resource isn't (fully) supported. Playback may still be possible, but without an audio or video component.
QMediaPlayer::NetworkError3A network error occurred.
QMediaPlayer::AccessDeniedError4There are not the appropriate permissions to play a media resource.
QMediaPlayer::ServiceMissingError5A valid playback service was not found, playback cannot proceed.
enum QMediaPlayer::Flagflags QMediaPlayer::Flags
ConstantValueDescription
QMediaPlayer::LowLatency0x01The player is expected to be used with simple audio formats, but playback should start without significant delay. Such playback service can be used for beeps, ringtones, etc.
QMediaPlayer::StreamPlayback0x02The player is expected to play
based streams. If passed to
constructor, the service supporting streams playback will be chosen.
QMediaPlayer::VideoSurface0x04The player is expected to be able to render to a
The Flags type is a typedef for &Flag&. It stores an OR combination of Flag values.
enum QMediaPlayer::MediaStatus
Defines the status of a media player's current media.
ConstantValueDescription
QMediaPlayer::UnknownMediaStatus0The status of the media cannot be determined.
QMediaPlayer::NoMedia1The is no current media. The player is in the .
QMediaPlayer::LoadingMedia2The current media is being loaded. The player may be in any state.
QMediaPlayer::LoadedMedia3The current media has been loaded. The player is in the .
QMediaPlayer::StalledMedia4Playback of the current media has stalled due to insufficient buffering or some other temporary interruption. The player is in the
QMediaPlayer::BufferingMedia5The player is buffering data but has enough data buffered for playback to continue for the immediate future. The player is in the
QMediaPlayer::BufferedMedia6The player has fully buffered the current media. The player is in the
QMediaPlayer::EndOfMedia7Playback has reached the end of the current media. The player is in the .
QMediaPlayer::InvalidMedia8The current media cannot be played. The player is in the .
enum QMediaPlayer::State
Defines the current state of a media player.
ConstantValueDescription
QMediaPlayer::StoppedState0The media player is not playing content, playback will begin from the start of the current track.
QMediaPlayer::PlayingState1The media player is currently playing content.
QMediaPlayer::PausedState2The media player has paused playback, playback of the current track will resume from the position the player was paused at.
Property Documentation
audioAvailable : const bool
This property holds the audio availabilty status for the current media.
As the life time of
can be longer than the playback of one , this property may change over time, the
signal can be used to monitor it's status.
Access functions:
bool isAudioAvailable() const
Notifier signal:
void (bool available)
audioRole :
This property holds the role of the audio stream played by the media player.
It can be set to specify the type of audio being played, allowing the system to make appropriate decisions when it comes to volume, routing or post-processing.
The audio role must be set before calling ().
This property was introduced in
Access functions:
QAudio::Role audioRole() const
void setAudioRole(QAudio::Role audioRole)
See also ().
bufferStatus : const int
This property holds the percentage of the temporary buffer filled before playback begins or resumes, from
(empty) to
When the player this property holds the percentage of the temporary buffer that is filled. The buffer will need to reach 100% filled before playback can start or resume, at which time () will return
or . If the value is anything lower than 100, () will return .
Access functions:
int bufferStatus() const
Notifier signal:
void (int percentFilled)
See also ().
currentMedia : const
This property holds the current active media content being played by the player object. This value could be different from QMediaPlayer::media property if a playlist is used. In this case currentMedia indicates the current media content being processed by the player, while QMediaPlayer::media property contains the original playlist.
Access functions:
QMediaContent currentMedia() const
Notifier signal:
void (const QMediaContent &media)
duration : const
This property holds the duration of the current media.
The value is the total playback time in milliseconds of the current media. The value may change across the life time of the
object and may not be available when initial playback begins, connect to the () signal to receive status notifications.
Access functions:
qint64 duration() const
Notifier signal:
void (qint64 duration)
error : const
This property holds a string describing the last error condition.
Access functions:
QString errorString() const
See also ().
This property holds the active media source being used by the player object.
The player object will use the
for selection of the content to be played.
By default this property has a null .
Setting this property to a null
will cause the player to discard all information relating to the current media source and to cease all I/O operations related to that media.
Access functions:
QMediaContent media() const
void (const QMediaContent &media, QIODevice *stream = Q_NULLPTR)
Notifier signal:
void (const QMediaContent &media)
mediaStatus : const
This property holds the status of the current media stream.
The stream status describes how the playback of the current stream is progressing.
By default this property is
Access functions:
MediaStatus mediaStatus() const
Notifier signal:
void (QMediaPlayer::MediaStatus status)
See also .
muted : bool
This property holds the muted state of the current media.
The value will be true if the play otherwise false.
Access functions:
bool isMuted() const
void setMuted(bool muted)
Notifier signal:
void (bool muted)
playbackRate :
This property holds the playback rate of the current media.
This value is a multiplier applied to the media's standard play rate. By default this value is 1.0, indicating that the media is playing at the standard pace. Values higher than 1.0 will increase the rate of play. Values less than zero can be set and indicate the media will rewind at the multiplier of the standard pace.
Not all playback services support change of the playback rate. It is framework defined as to the status and quality of audio and video while fast forwarding or rewinding.
Access functions:
qreal playbackRate() const
void setPlaybackRate(qreal rate)
Notifier signal:
void (qreal rate)
playlist :
This property holds the media playlist being used by the player object.
The player object will use the current playlist item for selection of the content to be played.
By default this property is set to null.
If the media playlist is used as a source,
is updated with a current playlist item. The current source should be selected with (int) instead of (), otherwise the current playlist will be discarded.
Access functions:
QMediaPlaylist *playlist() const
void setPlaylist(QMediaPlaylist *playlist)
See also .
position :
This property holds the playback position of the current media.
The value is the current playback position, expressed in milliseconds since the beginning of the media. Periodically changes in the position will be indicated with the signal (), the interval between updates can be set with 's method ().
Access functions:
qint64 position() const
void setPosition(qint64 position)
Notifier signal:
void (qint64 position)
seekable : const bool
This property holds the seek-able status of the current media.
If seeking is supported this p false otherwise. The status of this property may change across the life time of the
object, use the
signal to monitor changes.
Access functions:
bool isSeekable() const
Notifier signal:
void (bool seekable)
state : const
This property holds the media player's playback state.
By default this property is QMediaPlayer::Stopped
Access functions:
State state() const
Notifier signal:
void (QMediaPlayer::State state)
See also (), (), (), and ().
videoAvailable : const bool
This property holds the video availability status for the current media.
If available, the
class can be used to view the video. As the life time of
can be longer than the playback of one , this property may change over time, the
signal can be used to monitor it's status.
Access functions:
bool isVideoAvailable() const
Notifier signal:
void (bool videoAvailable)
volume : int
This property holds the current playback volume.
The playback volume is linear in effect and the value can range from 0 - 100, values outside this range will be clamped.
Access functions:
int volume() const
void setVolume(int volume)
Notifier signal:
void (int volume)
Member Function Documentation
QMediaPlayer::QMediaPlayer( *parent = Q_NULLPTR,
flags = Flags())
Construct a
instance parented to parent and with flags.
QMediaPlayer::~QMediaPlayer()
Destroys the player object.
[signal] void QMediaPlayer::audioAvailableChanged(bool available)
Signals the availability of audio content has changed to available.
Note: Notifier signal for property .
[signal] void QMediaPlayer::audioRoleChanged( role)
Signals that the audio role of the media player has changed.
This function was introduced in
QMediaPlayer::availability() const
Reimplemented from ().
[signal] void QMediaPlayer::bufferStatusChanged(int percentFilled)
Signal the amount of the local buffer filled as a percentage by percentFilled.
Note: Notifier signal for property .
[signal] void QMediaPlayer::currentMediaChanged(const
Signals that the current playing content has been changed to media.
Note: Notifier signal for property . See also () and ().
QMediaPlayer::currentNetworkConfiguration() const
Returns the current network access point in use. If a default contructed
is returned this feature is not available or that none of the current supplied configurations are in use.
[signal] void QMediaPlayer::durationChanged( duration)
Signal the duration of the content has changed to duration, expressed in milliseconds.
Note: Notifier signal for property .
QMediaPlayer::error() const
Returns the current error state.
[signal] void QMediaPlayer::error( error)
Signals that an error condition has occurred.
Note: Signal error is overloaded in this class. To connect to this one using the function pointer syntax, you must specify the signal type in a static cast, as shown in this example:connect(mediaPlayer, static_cast&void(::*)(::Error)&(&::error),
[=](::Error error){
See also ().
QMediaPlayer::hasSupport(const
&mimeType, const
&codecs = QStringList(),
flags = Flags())
Returns the level of support a media player has for a mimeType and a set of codecs.
The flags argument allows additional requirements such as performance indicators to be specified.
[signal] void QMediaPlayer::mediaChanged(const
Signals that the media source has been changed to media.
Note: Notifier signal for property . See also () and ().
[signal] void QMediaPlayer::mediaStatusChanged( status)
Signals that the status of the current media has changed.
Note: Notifier signal for property . See also ().
*QMediaPlayer::mediaStream() const
Returns the stream source of media data.
This is only valid if a stream was passed to ().
See also ().
[signal] void QMediaPlayer::mutedChanged(bool muted)
Signal the mute state has changed to muted.
Note: Notifier signal for property .
[signal] void QMediaPlayer::networkConfigurationChanged(const
&configuration)
Signal that the active in use network access point has been changed to configuration and all subsequent network access will use this configuration.
[slot] void QMediaPlayer::pause()
Pause playing the current source.
[slot] void QMediaPlayer::play()
Start or resume playing the current source.
[signal] void QMediaPlayer::playbackRateChanged( rate)
Signals the
has changed to rate.
Note: Notifier signal for property .
[signal] void QMediaPlayer::positionChanged( position)
Signal the position of the content has changed to position, expressed in milliseconds.
Note: Notifier signal for property .
[signal] void QMediaPlayer::seekableChanged(bool seekable)
Signals the seekable status of the player object has changed.
Note: Notifier signal for property .
[slot] void QMediaPlayer::setMedia(const
*stream = Q_NULLPTR)
Sets the current media source.
If a stream media data will be read from it instead of resolving the media source. In this case the media source may still be used to resolve additional information about the media such as mime type.
Setting the media to a null
will cause the player to discard all information relating to the current media source and to cease all I/O operations related to that media.
Note: This function returns immediately after recording the specified source of the media. It does not wait for the media to finish loading and does not check for errors. Listen for the () and () signals to be notified when the media is loaded and when an error occurs during loading.Note: Setter function for property . See also ().
[slot] void QMediaPlayer::setNetworkConfigurations(const && &configurations)
Sets the network access points for remote media playback. configurations contains, in ascending preferential order, a list of configuration that can be used for network access.
This will invalidate the choice of previous configurations.
void QMediaPlayer::setVideoOutput( *output)
video output to the media player.
If the media player has already video output attached, it will be replaced with a new one.
void QMediaPlayer::setVideoOutput( *output)
video output to the media player.
If the media player has already video output attached, it will be replaced with a new one.
void QMediaPlayer::setVideoOutput( *surface)
Sets a video surface as the video output of a media player.
If a video output has already been set on the media player the new surface will replace it.
[signal] void QMediaPlayer::stateChanged( state)
Signal the state of the Player object has changed.
Note: Notifier signal for property .
[slot] void QMediaPlayer::stop()
Stop playing, and reset the play position to the beginning.
&& QMediaPlayer::supportedAudioRoles() const
Returns a list of supported audio roles.
If setting the audio role is not supported, an empty list is returned.
This function was introduced in
See also .
[signal] void QMediaPlayer::videoAvailableChanged(bool videoAvailable)
Signal the availability of visual content has changed to videoAvailable.
Note: Notifier signal for property .
[signal] void QMediaPlayer::volumeChanged(int volume)
Signal the playback volume has changed to volume.
Note: Notifier signal for property .
& 2016 The Qt Company Ltd.
Documentation contributions included herein are the copyrights of
their respective owners.
The documentation provided herein is licensed under the terms of the
as published by the Free Software Foundation.
Qt and respective logos are trademarks of The Qt Company Ltd.
in Finland and/or other countries worldwide. All other trademarks are property
of their respective owners.

我要回帖

更多关于 qmediaplayer用法 的文章

 

随机推荐