代码-ios音频后台播放,怎么实现(在线)

问题描述

ios音频后台播放,怎么实现(在线)
ios音频后台播放,怎么实现,在线播放的
最好有直接执行的代码

解决方案

IOS后台运行 之 后台播放音乐

iOS后台播放音乐

解决方案二:
使用服务,即Service就可以满足你的要求。
给你我以前自己写的示例:

import java.util.List;import android.annotation.SuppressLint;import android.app.Service;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.media.MediaPlayer;import android.media.MediaPlayer.OnCompletionListener;import android.media.MediaPlayer.OnPreparedListener;import android.os.Handler;import android.os.IBinder;import android.os.Message;import android.util.Log;import com.hs.leozheng.phonelinkhs.MusicListActivity;import com.hs.leozheng.phonelinkhs.AudioMediaInfo;import com.hs.leozheng.phonelinkhs.AppConstant;/*** * leo * 音乐播放服务 */@SuppressLint(""NewApi"")public class PlayerService extends Service {    private MediaPlayer mediaPlayer;    // 媒体播放器对象    private String path;                // 音乐文件路径    private int msg;    private boolean isPause;            // 暂停状态    private int current = 0;            // 记录当前正在播放的音乐    private List<AudioMediaInfo> mp3Infos;      // 存放 AudioMediaInfo 对象的集合    private int status = 3;             // 播放状态,默认为顺序播放    private MyReceiver myReceiver;      // 自定义广播接收器    private int currentTime;            // 当前播放进度    private int duration;               // 播放长度    /**     * handler 用来接收消息,来发送广播更新播放时间     */    @SuppressLint(""HandlerLeak"")    private Handler handler = new Handler() {        @Override        public void handleMessage(Message msg) {            if (msg.what == 1) {                if(mediaPlayer != null) {                    currentTime = mediaPlayer.getCurrentPosition(); // 获取当前音乐播放的位置                    duration = mediaPlayer.getDuration();                    Intent intent = new Intent();                    intent.setAction(AppConstant.AUDIO_SEND_CURRENT);                    intent.putExtra(""currentTime"" currentTime);                    intent.putExtra(""totalTime"" duration);                    sendBroadcast(intent); // 给 PlayerActivity 发送广播                    handler.sendEmptyMessageDelayed(1 100);                }            }        };    };    @Override    public void onCreate() {        super.onCreate();        Log.i(""service""service created"");        mediaPlayer = new MediaPlayer();        mp3Infos = MusicListActivity.getMp3Infos(PlayerService.this);        myReceiver = new MyReceiver();        IntentFilter filter = new IntentFilter();        filter.addAction(AppConstant.AUDIO_CTRL_ACTION);        registerReceiver(myReceiver filter);        /**         * 设置音乐播放完成时的监听器         */        mediaPlayer.setOnCompletionListener(new OnCompletionListener() {            @Override            public void onCompletion(MediaPlayer mp) {                if (1 == status) {          // 单曲循环                    mediaPlayer.start();                } else if (2 == status) {   // 全部循环                    current++;                    if(current > mp3Infos.size() - 1) { // 变为第一首的位置继续播放                        current = 0;                    }                    path = mp3Infos.get(current).GetUrl();                    Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);                    sendIntent.putExtra(""current"" current);                    sendIntent.putExtra(""url"" path);                    sendIntent.putExtra(""total"" mp3Infos.size());                    // 发送广播,将被 Activity 组件中的 BroadcastReceiver 接收到                    sendBroadcast(sendIntent);                    play(0);                } else if (3 == status) {   // 顺序播放                    current++;              // 下一首位置                    if (current <= mp3Infos.size() - 1) {                        path = mp3Infos.get(current).GetUrl();                        Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);                        sendIntent.putExtra(""current"" current);                        sendIntent.putExtra(""url"" path);                        sendIntent.putExtra(""total"" mp3Infos.size());                        sendBroadcast(sendIntent);                        play(0);                    }else {                        mediaPlayer.seekTo(0);                        current = 0;                        path = mp3Infos.get(current).GetUrl();                        Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);                        sendIntent.putExtra(""current"" current);                        sendIntent.putExtra(""url"" path);                        sendIntent.putExtra(""total"" mp3Infos.size());                        sendBroadcast(sendIntent);                    }                } else if (4 == status) {   // 随机播放                    current = getRandomIndex(mp3Infos.size() - 1);                    path = mp3Infos.get(current).GetUrl();                    Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);                    sendIntent.putExtra(""current"" current);                    sendIntent.putExtra(""url"" path);                    sendIntent.putExtra(""total"" mp3Infos.size());                    sendBroadcast(sendIntent);                    play(0);                }            }        });    }    /**     * 获取随机位置     */    protected int getRandomIndex(int end) {        int index = (int) (Math.random() * end);        return index;    }    @Override    public IBinder onBind(Intent arg0) {        return null;    }    @SuppressWarnings(""deprecation"")    @Override    public void onStart(Intent intent int startId) {        path = intent.getStringExtra(""url"");                // 歌曲路径        current = intent.getIntExtra(""listPosition"" -1);   // 当前播放歌曲的在 mp3Infos 的位置        Log.i(""Play Service""onStart current is: "" + Integer.toString(current));        msg = intent.getIntExtra(""MSG"" 0);                 // 播放信息        AppConstant.PlayerMsg msgEnum = AppConstant.PlayerMsg.values()[msg];        if (AppConstant.PlayerMsg.PLAY_MSG == msgEnum) {    // 直接播放音乐            Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);            sendIntent.putExtra(""current"" current);            sendIntent.putExtra(""url"" path);            sendIntent.putExtra(""total"" mp3Infos.size());            // 发送广播,将被 Activity 组件中的 BroadcastReceiver 接收到            sendBroadcast(sendIntent);            play(0);        }        else if (AppConstant.PlayerMsg.PAUSE_MSG == msgEnum) {          // 暂停            pause();        }        else if (AppConstant.PlayerMsg.STOP_MSG == msgEnum) {           // 停止            stop();        }        else if (AppConstant.PlayerMsg.CONTINUE_MSG == msgEnum) {       // 继续播放            resume();        }        else if (AppConstant.PlayerMsg.PRIVIOUS_MSG == msgEnum) {       // 上一首            previous();        }        else if (AppConstant.PlayerMsg.NEXT_MSG == msgEnum) {           // 下一首            next();        }        else if (AppConstant.PlayerMsg.PROGRESS_CHANGE == msgEnum) {    // 进度更新            currentTime = intent.getIntExtra(""progress"" -1);            play(currentTime);        }        else if (AppConstant.PlayerMsg.PLAYING_MSG == msgEnum) {            handler.sendEmptyMessage(1);        }        super.onStart(intent startId);    }    /**     * 播放音乐     *     * @param position     */    private void play(int currentTime) {        try {            mediaPlayer.reset();                // 把各项参数恢复到初始状态            mediaPlayer.setDataSource(path);            Intent commonCtrl_intent = new Intent();            commonCtrl_intent.setAction(AppConstant.COMMON_UI_MSG);            commonCtrl_intent.putExtra(""ACTION""UIPlayingFilename"");            // 对 URL 进行处理: 保显示文件名不显示目录            int find = path.lastIndexOf('/') + 1;            String strFilename = null;            if(-1 != find)            {                strFilename = path.substring(find);                commonCtrl_intent.putExtra(""filename"" strFilename);                sendBroadcast(commonCtrl_intent);            }            mediaPlayer.prepare();              // 进行缓冲            mediaPlayer.setOnPreparedListener(new PreparedListener(currentTime));   // 注册一个监听器            handler.sendEmptyMessage(1);        } catch (Exception e) {            e.printStackTrace();        }    }    /**     * 暂停音乐     */    private void pause() {        if (mediaPlayer != null && mediaPlayer.isPlaying()) {            mediaPlayer.pause();            isPause = true;            Intent commonCtrl_intent = new Intent();            commonCtrl_intent.setAction(AppConstant.COMMON_UI_MSG);            commonCtrl_intent.putExtra(""ACTION""UIPlayingStatus"");            commonCtrl_intent.putExtra(""playingStatus"" 2);            sendBroadcast(commonCtrl_intent);        }    }    private void resume() {        if (isPause) {            mediaPlayer.start();            isPause = false;            Intent commonCtrl_intent = new Intent();            commonCtrl_intent.setAction(AppConstant.COMMON_UI_MSG);            commonCtrl_intent.putExtra(""ACTION""UIPlayingStatus"");            commonCtrl_intent.putExtra(""playingStatus"" 1);            sendBroadcast(commonCtrl_intent);        }    }    /**     * 上一首     */    private void previous() {        int size = mp3Infos.size();        if((current - 1) >= 0) {            current--;        }        else {            current = size - 1;        }        path = mp3Infos.get(current).GetUrl();        Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);        sendIntent.putExtra(""current"" current);        sendIntent.putExtra(""url"" path);        sendIntent.putExtra(""total"" size);        // 发送广播,将被 Activity 组件中的 BroadcastReceiver 接收到        sendBroadcast(sendIntent);        play(0);    }    /**     * 下一首     */    private void next() {        int size = mp3Infos.size();        if((current + 1) <= (size - 1)) {            current++;        }        else {            current = 0;        }        path = mp3Infos.get(current).GetUrl();        Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);        sendIntent.putExtra(""current"" current);        sendIntent.putExtra(""url"" path);        sendIntent.putExtra(""total"" size);        // 发送广播,将被 Activity 组件中的 BroadcastReceiver 接收到        sendBroadcast(sendIntent);        play(0);    }    /**     * 停止音乐     */    private void stop() {        if (mediaPlayer != null) {            mediaPlayer.stop();            try {                mediaPlayer.prepare(); // 在调用 stop 后如果需要再次通过 start 进行播放需要之前调用 prepare 函数            } catch (Exception e) {                e.printStackTrace();            }            Intent commonCtrl_intent = new Intent();            commonCtrl_intent.setAction(AppConstant.COMMON_UI_MSG);            commonCtrl_intent.putExtra(""ACTION""UIPlayingStatus"");            commonCtrl_intent.putExtra(""playingStatus"" 3);            sendBroadcast(commonCtrl_intent);        }    }    @Override    public void onDestroy() {        if (mediaPlayer != null) {            mediaPlayer.stop();            mediaPlayer.release();            mediaPlayer = null;        }    }    /**     *     * 实现一个 OnPrepareLister 接口当音乐准备好的时候开始播放     *     */    private final class PreparedListener implements OnPreparedListener {        private int currentTime;        public PreparedListener(int currentTime) {            this.currentTime = currentTime;        }        @Override        public void onPrepared(MediaPlayer mp) {            mediaPlayer.start();    // 开始播放            if (currentTime > 0) {  // 如果音乐不是从头播放                mediaPlayer.seekTo(currentTime);            }            Intent intent = new Intent();            intent.setAction(AppConstant.AUDIO_SEND_DURATION);            duration = mediaPlayer.getDuration();            intent.putExtra(""duration"" duration);  // 通过 Intent 来传递歌曲的总长度            sendBroadcast(intent);        }    }    public class MyReceiver extends BroadcastReceiver {        @Override        public void onReceive(Context context Intent intent) {            AppConstant.PlayerMsg msgEnum = AppConstant.PlayerMsg.APP_CONSTANT_MAX;            String action = intent.getAction();            int msg = intent.getIntExtra(""MSG"" -1);            int mode = intent.getIntExtra(""mode"" 3);            if(msg > 0) {                msgEnum = AppConstant.PlayerMsg.values()[msg];            }            if(action.equals(AppConstant.AUDIO_CTRL_ACTION)) {                Log.v(""Play Service""Control: "" + Integer.toString(msg));                if(msgEnum == AppConstant.PlayerMsg.PRIVIOUS_MSG)                {                    Log.v(""Play Service""Control.Prev"");                    previous();                }                else if(msgEnum == AppConstant.PlayerMsg.NEXT_MSG)                {                    Log.v(""Play Service""Control.Next"");                    next();                }                else if(msgEnum == AppConstant.PlayerMsg.PLAY_MODE)                {                    Log.v(""Play Service""Control.Mode: "" + Integer.toString(mode));                }                else if(msgEnum == AppConstant.PlayerMsg.CONTINUE_MSG)                {                    Log.v(""Play Service""Control.Continue"");                    resume();                }                else if(msgEnum == AppConstant.PlayerMsg.PAUSE_MSG)                {                    Log.v(""Play Service""Control.Pause"");                    pause();                }            }        }    }}

调用 方式:

Intent intent = new Intent();intent.putExtra(""url"" audioMediaInfo.GetUrl());   // 参数可要、可不要intent.putExtra(""listPosition"" positionSelected/*getPlayingIndex(audioMediaInfo.GetUrl())*/);intent.putExtra(""MSG"" AppConstant.PlayerMsg.PLAY_MSG.ordinal());intent.setClass(MusicListActivity.this PlayerService.class);startService(intent); 

解决方案三:
iOS 后台运行,百度的话,会有好多的博客,都是可以实现的

解决方案四:
http://blog.csdn.net/capacity_bo/article/details/44943005

解决方案五:
在AppDelegate中添加:
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

并且在info.plist中添加 Localization native development region

这样就实现了

解决方案六:
在AppDelegate中添加:
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

并且在info.plist中添加 Localization native development region

这样就实现了

解决方案七:
留个邮箱 我发给你一个

时间: 2024-08-27 03:56:35

代码-ios音频后台播放,怎么实现(在线)的相关文章

iOS音频的后台播放总结(后台网络请求歌曲,Remote控制,锁屏封面,各种打断)

在没有网络的情况下,音频的后台播放比较简单,google一下可以搜到很多资料,但是如果每次歌曲的请求都是通过网络,就不成了,有时可以也扛不了几首,这里总结下实现方法,可以实现像电台一样的功能,后台播放,网络请求歌曲,Remote控制,锁屏有封面,电话和听歌打断处理等.     初始化AudioSession和基本配置 音频播放器采用的AVPlayer ,自己进行了功能封装,暂且不谈,在程序启动的时候需要配置AudioSession,AudioSession负责应用音频的设置,比如支不支持后台,打

IOS音频播放(二)

第二部分转载自: 码农人生 前言 本篇为<iOS音频播放>系列的第二篇. 在实施前一篇中所述的7个步骤之前还必须面对一个麻烦的问题,AudioSession. AudioSession简介 AudioSession这个玩意的主要功能包括以下几点(图片来自官方文档): 确定你的app如何使用音频(是播放?还是录音?) 为你的app选择合适的输入输出设备(比如输入用的麦克风,输出是耳机.手机功放或者airplay) 协调你的app的音频播放和系统以及其他app行为(例如有电话时需要打断,电话结束时

与众不同windows phone (15) Media(媒体)之后台播放音频

介绍 与众不同 windows phone 7.5 (sdk 7.1) 之媒体 通过 AudioPlayerAgent 实现在后台播放音频 示例 演示如何通过后台代理的方式来实现音频在后台的播放 1.后台代理 MyAudioPlayerAgent/AudioPlayer.cs /* * 本例演示如何播放后台音频(以 AudioPlayerAgent 为例,另 AudioStreamingAgent 用于流式播放音频) * 建议使用 AudioPlaybackAgent 类型的模板创建此项目 *

IOS音频播放(一)

第一部分转载自: 码农人生 iOS音频播放 (一):概述 Audio Playback in iOS (Part 1) : Introduction 前言 从事音乐相关的app开发也已经有一段时日了,在这过程中app的播放器几经修改我也因此对于iOS下的音频播放实现有了一定的研究.写这个系列的博客目的一方面希望能够抛砖引玉,另一方面也是希望能帮助国内其他的iOS开发者和爱好者少走弯路(我自己就遇到了不少的坑=.=). 本篇为<iOS音频播放>系列的第一篇,主要将对iOS下实现音频播放的方法进行

与众不同 windows phone (15) - Media(媒体)之后台播放音频

原文:与众不同 windows phone (15) - Media(媒体)之后台播放音频 [索引页][源码下载] 与众不同 windows phone (15) - Media(媒体)之后台播放音频 作者:webabcd 介绍与众不同 windows phone 7.5 (sdk 7.1) 之媒体 通过 AudioPlayerAgent 实现在后台播放音频 示例演示如何通过后台代理的方式来实现音频在后台的播放1.后台代理MyAudioPlayerAgent/AudioPlayer.cs /*

ios-HTML5 Audio多音频同时播放延迟问题

问题描述 HTML5 Audio多音频同时播放延迟问题 平台:安卓.IOS 开发语言:HTML5 问题描述:多个音频同时播放出现6~16ms左右的延迟,希望能缩到2ms内 问题代码: function play( url1,url2,url3,url4,url5,url6,url7 ){ p = plus.audio.createPlayer(url1); p1 = plus.audio.createPlayer(url2); p2 = plus.audio.createPlayer(url3)

Windows 8 Store Apps学习(65) 后台任务: 音乐的后台播放和控制

介绍 重新想象 Windows 8 Store Apps 之 后台任务 音乐的后台播放和控制 示例 用于保存每首音乐的相关信息的对象 BackgroundTask/SongModel.cs /* * 用于保存每首音乐的相关信息 */ using System; using System.Threading.Tasks; using Windows.Storage; namespace XamlDemo.BackgroundTask { public class SongModel { /// <

iOS 7后台多任务 (Multitasking) 的变化

简单来说,这玩意是对开发者友好,但对设备不友好的(可能会偷偷摸摸地占用流量和电量). 对用户来说,如果你带宽够,对发热不敏感的话,会得到更好的应用体验. 从 iOS 4 开始,应用就可以在退到后台后,继续运行一小段时间了(10 分钟). 此外还可以把自己声明为需要在后台运行,就能不限时地运行了.不过限制为播放音乐.使用 GPS 等.值得一提的是,有的应用为了达到后台不限时运行的目的,在后台播放无声的音乐(审核不一定会被发现). iOS 5 开始又多了一种类型:下载报刊杂志. 然后 iOS 7 则

关于SWF格式视频在IE8浏览器中不能播放问题,在线等,谢谢

问题描述 关于SWF格式视频在IE8浏览器中不能播放问题,在线等,谢谢 SWF格式视频在火狐和谷歌都可以正常播放,IE9及以上版本也可以播放,但是在IE8下就不可以播放,请问什么原因? <script src="${ct}/businessConsole/javascript/jquery-easyui-1.3.2/jquery-1.8.0.min.js"></script> <script src="${ct}/plugins/jwplayer