iOS後臺持續播放音樂
之前在App Store上架了一個音樂播放器軟體,用的是AVPlayer做的音樂播放器。很多使用者反映沒有後臺播放,最近決定更新一下。
注意,重點是持續後臺播放,網路歌曲也可以,重點是持續播放,後臺播放很簡單,但是後臺持續播放,則需要做一些處理,申請後臺id,才能實現持續播放。
1.開啟所需要的後臺模式:
<pre>選中Targets-->Capabilities-->BackgroundModes-->ON,
並勾選Audio and AirPlay選項,如下圖
設定後臺模式
</pre>
2.在Appdelegate.m的applicationWillResignActive:方法中啟用後臺播放,程式碼如下:
<pre>
-(void)applicationWillResignActive:(UIApplication *)application
{
//開啟後臺處理多媒體事件
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
AVAudioSession *session=[AVAudioSession sharedInstance];
[session setActive:YES error:nil];
//後臺播放
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
//這樣做,可以在按home鍵進入後臺後 ,播放一段時間,幾分鐘吧。但是不能持續播放網路歌曲,若需要持續播放網路歌曲,還需要申請後臺任務id,具體做法是:
_bgTaskId=[AppDelegate backgroundPlayerID:_bgTaskId];
//其中的_bgTaskId是後臺任務UIBackgroundTaskIdentifier _bgTaskId;
}
實現一下backgroundPlayerID:這個方法:
+(UIBackgroundTaskIdentifier)backgroundPlayerID:(UIBackgroundTaskIdentifier)backTaskId
{
//設定並激活音訊會話類別
AVAudioSession *session=[AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
[session setActive:YES error:nil];
//允許應用程式接收遠端控制
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
//設定後臺任務ID
UIBackgroundTaskIdentifier newTaskId=UIBackgroundTaskInvalid;
newTaskId=[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
if(newTaskId!=UIBackgroundTaskInvalid&&backTaskId!=UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:backTaskId];
}
return newTaskId;
}
</pre>
3.處理中斷事件,如電話,微信語音等。
原理是,在音樂播放被中斷時,暫停播放,在中斷完成後,開始播放。具體做法是:
<pre>
-->在通知中心註冊一個事件中斷的通知:
//處理中斷事件的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterreption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
-->實現接收到中斷通知時的方法
//處理中斷事件
-(void)handleInterreption:(NSNotification *)sender
{
if(_played)
{
[self.playView.player pause];
_played=NO;
}
else
{
[self.playView.player play];
_played=YES;
}
}
</pre>
4.至此音樂後臺持續播放搞定,大功告成!現在可以開啟軟體播放一首歌曲,然後按home鍵回到後臺,音樂會繼續播放~
應簡友要求,在此貼出播放器程式碼:
簡單看下介面
list player now play info center-
PlayerViewController.h
#import "RootViewController.h"
#import "songInfoModel.h"
#import <AVFoundation/AVFoundation.h>
#import "PlayView.h"
#import "FMSongListModel.h"
@interface PlayerViewController : RootViewController
//下載連結
@property(nonatomic, strong)NSString *sourceURLString;
@property(nonatomic, copy)NSString *songname;
@property(nonatomic, copy)NSString *singerName;
@property(nonatomic, copy)NSString *songUrl;
@property(nonatomic, copy )NSString *songPicUrl;
@property(nonatomic, strong)songInfoModel *model;
@property(nonatomic,assign)NSInteger currentSongIndex;
@property(nonatomic,strong)NSArray *songArray;
+(instancetype)sharedPlayerController;
//重新整理播放的歌曲
-(void)refreshWithModel:(songInfoModel *)sim;
//停止播放
-(void)stop;
//暫停
-(void)pauseMusic;
@end
-
PlayerViewController.m
#import "PlayerViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "UIImageView+WebCache.h"
#import "mvListModel.h"
#import "PlayView.h"
#import "Word.h"
#import "auditionListModel.h"
#import "AFNetworking.h"
#import "QFHttpManager.h"
#import "QFHttpRequest.h"
#import <ShareSDK/ShareSDK.h>
#import "Maker.h"
#import <MediaPlayer/MediaPlayer.h>
#import "Constant.h"
#import "PopMenu.h"
#import "KxMenu.h"
#import "FMSongListModel.h"
#import "FMSongModel.h"
#import "MCDataEngine.h"
#import "ProgressHUD.h"
#import "DownloadViewController.h"
#import "DownloadModel.h"
#import "DownloadDBManager.h"
#import "FGGDownloadManager.h"
@interface PlayerViewController ()<UITableViewDataSource, UITableViewDelegate>{
UITableView *_tbView;
//分享選單
PopMenu *_menu;
UITapGestureRecognizer *_hideShareGesture;
//暫無歌詞的提示Label
UILabel *_noLrcLb;
}
@property(nonatomic,assign)MusicPlayType playType;
//標記分享選單是否顯示
@property(nonatomic,assign)BOOL isListShow;
//透明背景
@property(nonatomic,strong)UIView *shareBackView;
@property(nonatomic,copy)NSString *totalTime;
//當前歌詞行
@property(nonatomic,assign)NSInteger currentWordRow;
@property(nonatomic, strong)UIProgressView *videoProgress;
@property(nonatomic, strong)UIImageView *singerImageView;
@property(nonatomic,strong)NSArray *wordsArray;
@property(nonatomic, strong)AVPlayerItem *playerItem;
@property(nonatomic, strong)PlayView *playView;
@property(nonatomic,assign)BOOL played;
@property(nonatomic, strong)id playbackTimeObserver;
@end
static PlayerViewController *musicController=nil;
@implementation MusicPicViewController
+(instancetype)sharedPlayerController{
if(!musicController){
musicController=[[PlayerViewController alloc] init];
}
return musicController;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self setUp];
[self createBackView];
[self createUI];
[self createTitleView];
[self loadLyric];
[self createShareList];
[self preload];
[self load];
}
//初始化
-(void)setUp {
self.view.backgroundColor = [UIColor blackColor];
self.automaticallyAdjustsScrollViewInsets=NO;
self.navigationController.navigationBar.barStyle=UIBarStyleBlackOpaque;
_currentWordRow=0;
//預設迴圈播放
_playType=MusicPlayTypeRound;
}
#pragma mark - 背景圖片
-(void)createBackView {
UIImageView * backImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, kWidth, kHeight-64-90)];
backImageView.image = [UIImage returnImageWithName:@"bg.jpg"];
backImageView.alpha=0.7;
[self.view addSubview:backImageView];
}
- (void)createUI {
_playView = [[PlayView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight)];
[self.view addSubview:_playView];
__weak typeof(self) weakSelf=self;
_playView.nextBtnDidClickedBlock=^{
if(weakSelf.playType==MusicPlayTypeRandom)
[weakSelf randomNext];
else
[weakSelf next];
};
_playView.previousBtnDidClickedBlock=^{
if(weakSelf.playType==MusicPlayTypeRandom)
[weakSelf randomNext];
else
[weakSelf previous];
};
//切換播放模式
_playView.typeBtnDidClickedBlock=^(UIButton *sender){
if(weakSelf.playType==MusicPlayTypeRound){
[sender setTitle:@"單曲" forState:UIControlStateNormal];
//[sender setImage:[UIImage imageNamed:@"single"] forState:UIControlStateNormal];
weakSelf.playType=MusicPlayTypeSingle;
[ProgressHUD showSuccess:@"單曲迴圈"];
}else if(weakSelf.playType==MusicPlayTypeSingle){
[sender setTitle:@"隨機" forState:UIControlStateNormal];
//[sender setImage:[UIImage imageNamed:@"random"] forState:UIControlStateNormal];
weakSelf.playType=MusicPlayTypeRandom;
[ProgressHUD showSuccess:@"隨機播放"];
}else if(weakSelf.playType==MusicPlayTypeRandom){
[sender setTitle:@"迴圈" forState:UIControlStateNormal];
//[sender setImage:[UIImage imageNamed:@"round"] forState:UIControlStateNormal];
weakSelf.playType=MusicPlayTypeRound;
[ProgressHUD showSuccess:@"迴圈播放"];
}
};
[self.playView.slider addTarget:self action:@selector(videoSliderChangeValue:) forControlEvents:UIControlEventValueChanged];
self.videoProgress=[[UIProgressView alloc] initWithFrame:CGRectMake(93, kHeight-48, kWidth-180, 15)];
_videoProgress.alpha=0.6;
_videoProgress.progressTintColor=RGB(76, 168, 76);
[self.view addSubview:_videoProgress];
[self.playView.playButton addTarget:self action:@selector(onClickChangeState) forControlEvents:UIControlEventTouchUpInside];
UIImageView * singerImageView =[[UIImageView alloc] initWithFrame:CGRectMake(10, kHeight-80, 60, 60)];
singerImageView.tag=kSingerImageTag;
self.singerImageView = singerImageView;
if(self.model.mvListArray) {
mvListModel * model=nil;
if ([self.model.mvListArray count]){
model= [self.model.mvListArray firstObject];
}
singerImageView.image=[UIImage imageNamed:@"defaultNomusic.png"];
NSURL *url=nil;
if(model.picUrl.length>0){
url=[NSURL URLWithString:model.picUrl];
}
if(url){
[singerImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"defaultNomusic.png"]];
}
}else{
NSURL *url=[NSURL URLWithString:self.songPicUrl];
[singerImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"defaultNomusic.png"]];
}
singerImageView.clipsToBounds = YES;
singerImageView.layer.cornerRadius = 30;
[self.view addSubview:singerImageView];
//歌手頭像迴圈滾動
[self repeadRatation];
_tbView=[[UITableView alloc]initWithFrame:CGRectMake(10, 64, kWidth-20,kHeight-64-90) style:UITableViewStylePlain];
_tbView.delegate=self;
_tbView.dataSource=self;
_tbView.separatorStyle=UITableViewCellSeparatorStyleNone;
[self.view addSubview:_tbView];
_tbView.showsVerticalScrollIndicator=NO;
_tbView.backgroundColor=[UIColor clearColor];
//暫無歌詞的label
_noLrcLb=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
_noLrcLb.center=self.view.center;
_noLrcLb.backgroundColor=[UIColor clearColor];
_noLrcLb.textAlignment=NSTextAlignmentCenter;
_noLrcLb.font=[UIFont systemFontOfSize:16];
_noLrcLb.textColor=[UIColor whiteColor];
[self.view addSubview:_noLrcLb];
if(_wordsArray.count>0){
_noLrcLb.text=nil;
}else{
_noLrcLb.text=@"暫無歌詞~";
}
}
-(void)createTitleView{
UILabel *statusLb=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, kWidth, 64)];
statusLb.backgroundColor=RGB(76, 168, 76);
[self.view addSubview:statusLb];
UILabel * songlabel = [[UILabel alloc] initWithFrame:CGRectMake(40,15, kWidth-80, 34)];
songlabel.numberOfLines=2;
songlabel.tag=kSongNameTag;
songlabel.text = self.model.name;
songlabel.font = [UIFont boldSystemFontOfSize:15];
songlabel.adjustsFontSizeToFitWidth=YES;
songlabel.textColor = [UIColor whiteColor];
songlabel.textAlignment = NSTextAlignmentCenter;
songlabel.backgroundColor=[UIColor clearColor];
[self.view addSubview:songlabel];
UILabel * singerLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 50, kWidth-80, 10)];
singerLabel.tag=kSingerNameTag;
singerLabel.text = self.model.singerName;
singerLabel.font = [UIFont systemFontOfSize:12];
singerLabel.textColor = [UIColor whiteColor];
singerLabel.textAlignment = NSTextAlignmentCenter;
singerLabel.backgroundColor=[UIColor clearColor];
[self.view addSubview:singerLabel];
UIButton *menuBtn=[[UIButton alloc]initWithFrame:CGRectMake(kWidth-40, 30, 20, 16)];
[menuBtn setImage:[UIImage imageNamed:@"list"] forState:UIControlStateNormal];
[self.view addSubview:menuBtn];
[menuBtn addTarget:self action:@selector(showMenu:) forControlEvents:UIControlEventTouchUpInside];
UIButton * backButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 20, 30, 30)];
[backButton setImage:[UIImage returnImageWithName:@"back.png"] forState:UIControlStateNormal];
[backButton addTarget:self action:@selector(onClickBack) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:backButton];
}
#pragma mark - 載入歌詞
- (void)loadLyric{
NSString * singerName = self.model.singerName;
NSString * songName1 = self.model.name;
NSArray * songNameArray = [songName1 componentsSeparatedByString:@"("];
NSString * songName = songNameArray[0];
NSString * lrcURL = [NSString stringWithFormat:SEARCH_LRC_URL, singerName, songName];
NSString * newLrcURL = [lrcURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[QFHttpManager sharedManager] addTask:newLrcURL delegate:self action:@selector(requestFinished:)];
}
#pragma mark - 下載歌詞
-(void)requestFinished:(QFHttpRequest*)Request{
NSString * str = [[NSString alloc] initWithData:Request.downloadData encoding:NSUTF8StringEncoding];
NSRange range = [str rangeOfString:@"<lrclink>/data2/lrc"];
//暫無歌詞的情況
if (!range.length){
_wordsArray=nil;
[_tbView reloadData];
_noLrcLb.text=@"暫無歌詞~";
return;
}
NSString * string = [str substringFromIndex:range.location];
NSArray * array = [string componentsSeparatedByString:@">"];
NSString * laststr = [NSString stringWithFormat:@"http://musicdata.baidu.com%@", array[1]];
NSArray * lrcArray = [laststr componentsSeparatedByString:@"<"];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:lrcArray[0]]];
NSString * downloadPath = [NSString stringWithFormat:@"%@/%@-%@.lrc", kLrcPath,self.model.singerName,self.model.name];
AFHTTPRequestOperation * requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
requestOperation.outputStream = [NSOutputStream outputStreamToFileAtPath:downloadPath append:NO];
[requestOperation start];
__weak typeof(self) weakSelf=self;
[requestOperation setCompletionBlock:^{
[weakSelf readFileOfPath:downloadPath];
}];
}
#pragma mark - 讀取歌詞
- (void)readFileOfPath:(NSString *)path{
self.wordsArray=[[Word alloc] wordsWithFilePath:path];
if(_wordsArray.count>0){
_noLrcLb.text=nil;
}
[_tbView reloadData];
}
#pragma mark - 建立分享檢視
-(void)createShareList {
NSArray *[email protected][@"微信",@"微信朋友圈",@"新浪微博",@"QQ",@"QQ空間",@"簡訊"];
NSArray *[email protected][@"wx",@"wx_friend",@"sina",@"qq",@"qzone",@"sms"];
NSMutableArray *array=[NSMutableArray array];
for(int i=0;i<names.count;i++){
MenuItem *item=[MenuItem itemWithTitle:names[i] iconName:images[i]];
[array addObject:item];
}
_menu=[[PopMenu alloc]initWithFrame:CGRectMake(kWidth/2-160, kHeight/2-150, 320, 320) items:array];
_menu.menuAnimationType=kPopMenuAnimationTypeNetEase;
_menu.backgroundColor=[UIColor clearColor];
__weak typeof(self) weakSelf=self;
_menu.didSelectedItemCompletion=^(MenuItem *item){
[weakSelf selectItem:item];
};
_hideShareGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showSharelist)];
}
#pragma mark - 顯示隱藏分享檢視
-(void)showSharelist{
[self loadSound];
if(_isListShow){
if ([[self.view gestureRecognizers] containsObject:_hideShareGesture])
{
[self.view removeGestureRecognizer:_hideShareGesture];
}
[_menu dismissMenu];
[_menu performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:0.3];
_isListShow=NO;
}
else{
_isListShow=YES;
[_menu showMenuAtView:self.view.window];
[self.view addGestureRecognizer:_hideShareGesture];
}
}
-(void)loadSound {
//播放音效
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"open.wav" ofType:nil]],&soundID);
//播放短音訊
AudioServicesPlaySystemSound(soundID);
//增加震動效果
//AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
-(void)preload{
if(self.model.auditionArray){
if(self.model.auditionArray.count>0){
auditionListModel * auModel = [[auditionListModel alloc] init];
if(self.model.auditionArray.count>0){
auModel = self.model.auditionArray[0];
}
if (self.model.auditionArray.count >= 2) {
auModel = self.model.auditionArray[1];
}
self.sourceURLString=auModel.url;
}
else{
self.sourceURLString=[[NSString stringWithFormat:@"file://%@/%@.mp3",kMusicPath,self.model.name] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
}else{
self.sourceURLString=self.songUrl;
}
}
-(void)load{
NSURL * playURL=[
相關推薦
iOS後臺持續播放音樂 中斷後持續播放
-(void)applicationWillResignActive:(UIApplication )application
{
//開啟後臺處理多媒體事件
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents
iOS後臺持續播放音樂
之前在App Store上架了一個音樂播放器軟體,用的是AVPlayer做的音樂播放器。很多使用者反映沒有後臺播放,最近決定更新一下。
注意,重點是持續後臺播放,網路歌曲也可以,重點是持續播放,後臺播放很簡單,但是後臺持續播放,則需要做一些處理,申請後臺id,才能實現持續播放。
1.開啟所需要的後臺模
解決手機端ios無法自動播放音樂的問題
function autoPlayAudio() {
wx.config({
// 配置資訊, 即使不正確也能使用 wx.ready
debug: false,
appId: '',
timest
IOS後臺播放音樂
har highlight 播放器 title ges round eas tro ios
IOS後臺播放音樂
博客分類:
IOS
http://www.apple.com.cn/developer/iphone/library/documentation/
ios-後臺播放音樂
iOS後臺播放音樂
1、在Info.plist中,新增"Required background modes"鍵,其值設定如下圖所示:
App plays audio or streams audio/video using AirPlay

2、新增AVFoundatio
IOS後臺執行 之 後臺播放音樂
iOS 4開始引入的multitask,我們可以實現像ipod程式那樣在後臺播放音訊了。如果音訊操作是用蘋果官方的AVFoundation.framework實現,像用AvAudioPlayer,AvPlayer播放的話,要實現完美的後臺音訊播放,依據app的功能需要,可能需要實現幾個關鍵的功能。
首先,播
手機影音第十五天,利用service實現後臺播放音樂,在通知欄顯示當前音樂信息等
手機影音 第十五天 利用service實現後臺播放音樂 在通知欄顯示當前音樂信息。 代碼已經托管到碼雲上,有興趣的小夥伴可以下載看看 https://git.oschina.net/joy_yuan/MobilePlayer 先來一張目前的音樂播放器的效果圖,當播
iOS音頻播放之AudioQueue(一):播放本地音樂
init方法 函數 完成 一起 utc getprop 應用 清洗 spl
AudioQueue簡單介紹
AudioStreamer說明
AudioQueue具體
小程式後臺播放音樂的使用
在app.js中建立一個唯一音訊控制物件,
如果在頁面中建立音訊控制物件, 會造成每次開啟這個頁面都會重新建立一個, 造成播放體驗不好, 例如暫停後, 點選開始, 不會接著上次位置播放的問題, 會先播放上一個音訊,再停止, 然後才開始本次音訊, 在此過程中體驗非常不好
App({
g
Android 後臺播放音樂Demo
開發流程:
A,建立服務把想使用的方法暴露出來。
B,定義介面,bind呼叫時返回物件,在service 開啟播放音樂實時更新進度條的位置
C,Activity 中建立hander 更新UI
【1】佈局
<LinearLayo
Android使用本地Service實現後臺播放音樂
配置檔案
<service android:name=".MyService"></service>
佈局
<Button
android:id="
iOS 藍芽實現音樂播放
簡介
在寫一個藍芽的專案裡邊,需要實現一個功能,按外設的按鈕實現音樂的播放暫停等功能,以及後臺播放。搜尋資料瞭解到
無論是iPod、iTouch、iPhone還是iPad都可以在iTunes購買音樂或新增本地音樂到音樂庫中同步到你的iOS裝置
iOS與微信端播放音樂問題
iOS不支援auido標籤自動播放autoplay屬性,我們需要所以我們需要在js中給audio標籤‘手 動’播放:
<audio src='xxx.mp3' autoPlay loop preload="auto" muted id="audio"><audio>
ios開發技術——播放系統wav格式的音樂
需要匯入的框架: AudioToolbox.framework
-(void)startWinPlayer
{
//定義URl,要播放的音樂檔案是win.wav
NSURL *audioPa
使用 AVAudioSession 實現後臺播放音樂
1. 前言
AVAudioSession是一個單例,無需例項化即可直接使用。AVAudioSession在各種音訊環境中起著非常重要的作用
針對不同的音訊應用場景,需要設定不同的音訊會
後臺播放音樂,防止iphone進入休眠,超詳細教程(可製作音樂鬧鐘)
// 後臺播放音樂
共有4個步驟,一個注意事項
步驟一:在resource資料夾下找到該專案的info.plist新增一個
Required background modes 的陣列
並在下面新增一個元素,其值為
App plays audio
步驟二:
iOS 簡單實用的音樂播放器,少年,自己做個歌單吧。。。。。。
我也不知道為什麼突然會想寫一下音樂播放器的,感覺應該挺好的玩,自己把自己喜歡的歌曲匯出來,用程式載入跑起來,那歌聽起來必定很帶感啊。。。。。。不過那首Love Story被我聽了無數遍。。。。。。聽吐了
ios微信瀏覽器自動播放音樂
自動播放 code lse art style clas touch remove bsp
//ios自動播放音樂
function audioAutoPlay(id){
var audio = document.getElementById(id),
iOS 語音類App播放自己的錄音完畢後,如何重新繼續播放音樂
前一篇文章講述了,iOS平臺如何錄音,以及如何播放錄音,也就是回放錄音。那麼,如果在你播放你的錄音之前,已經有音樂類的App在後臺正在播放音樂,這個時候一般的做法是先暫停音樂播放---->播放你自己的錄音---->繼續播放後臺的音樂。
其實,方法也比較簡單,就
Android後臺播放音樂(含通知欄操作)
功能①按下home鍵回到桌面時,音樂仍然可以播放,同時系統通知欄顯示當前音樂播放的狀態;②點選App介面的按鈕,可控制音樂播放的暫停繼續,同時系統通知欄播放狀態作相應改變;③點選系統通知欄按鈕控制音樂播放暫停,同時App介面播放狀態作相應調整;④App播放介面銷燬時,關閉音樂