2011-01-22 37 views
23

Tôi đã làm bài tập về nhà của tôi ... đã đọc ở đây, tài liệu, googling, stackoverflowing ... nhưng vẫn không có may mắn trong việc làm cho thanh âm thanh của tôi khi người dùng làm cho các ứng dụng đi vào nền.Làm cách nào để trình phát AVPlayer của tôi phát trong khi ứng dụng ở chế độ nền?

Điều tôi đã làm cho đến thời điểm này: Đã thêm UIBackgroundModes, âm thanh vào tệp plist.

Đầu tiên mã này:

radioAudio = [[AVAudioSession alloc] init]; 
[radioAudio setCategory:AVAudioSessionCategoryPlayback error:nil]; 
[radioAudio setActive:YES error:nil]; 

Sau đó này:

NSString *radioURL = @"http://xxx.xxx.xxx/radio.m3u"; 
radioPlayer = [[AVPlayer playerWithURL:[NSURL URLWithString:radioURL]] retain]; 

Nhưng ngay khi người dùng chạm vào nhà-nút, âm thanh của tôi qua đời.

Tôi cũng tìm thấy điều này, nhưng chưa thêm vào nhưng một số nội dung tôi đã đọc nói rằng không cần thiết;

newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL]; 
    if (newTaskId != UIBackgroundTaskInvalid && bgTaskId != UIBackgroundTaskInvalid) 
     [[UIApplication sharedApplication] endBackgroundTask: bgTaskId]; 
bgTaskId = newTaskId; 

Ngay bây giờ tôi không biết mình nên làm gì để AVPlayer cho phép radio phát trong khi người dùng thực hiện các nội dung khác trên điện thoại. Tôi đang thử nghiệm điều này trên iPhone 4 với 4.2. Xây dựng nó cho 4.0.

Bất kỳ ai có đề xuất nào tôi nên làm gì?

+0

Xem câu trả lời của tôi trong Quế này, bạn sẽ tìm thấy giải pháp của bạn [Nhấn vào đây để Xem trả lời] [1 ] [1]: http: // stackoverflow.com/questions/15470452/is-it-possible-to-play-video-sử dụng-avplayer-in-background –

Trả lời

40

Đã cùng một vấn đề, nhưng không tìm thấy một giải pháp cho điều này ..

Nhìn đây: https://devforums.apple.com/message/395049#395049

Nội dung của liên kết ở trên:


Thay thế APPNAME bằng tên ứng dụng của riêng bạn!

Im trên iOS 4.2.1

EDIT: Làm việc với iOS5 + 6 + 7 beta cho đến nay

Thêm UIBackgroundModes trong APPNAME-Info.plist, với việc lựa chọn ứng dụng chơi audio

Sau đó thêm khuôn khổ AudioToolBox vào khung thư mục.

Trong APPNAMEAppDelegate.h add:

#import <AVFoundation/AVFoundation.h> 
#import <AudioToolbox/AudioToolbox.h> 

để nó trông như thế này:

... 
#import <UIKit/UIKit.h> 
#import <AVFoundation/AVFoundation.h> 
#import <AudioToolbox/AudioToolbox.h> 
... 

Trong APPNAMEAppDelegate.m thêm như sau:

// Set AudioSession 
NSError *sessionError = nil; 
[[AVAudioSession sharedInstance] setDelegate:self]; 
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError]; 

/* Pick any one of them */ 
// 1. Overriding the output audio route 
//UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker; 
//AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride); 

// 2. Changing the default output audio route 
UInt32 doChangeDefaultRoute = 1; 
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute); 

vào

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 

nhưng trước hai dòng:

[self.window addSubview:viewController.view]; 
[self.window makeKeyAndVisible]; 

Xây dựng dự án của bạn và xem nếu theres bất kỳ lỗi, Nếu không, hãy thử gỡ lỗi trên thiết bị insted của Simulator, nó CAN lỗi trên mô phỏng.

Hy vọng điều này giúp những người khác với cùng một vấn đề ..

+2

Cảm ơn bạn Patrick R! ! :) –

+0

Chào mừng bạn :) –

+0

Cảm ơn bạn Patrik R! Công trinh! –

10

tôi đã thực hiện thành công chạy âm thanh trong nền bằng cách thêm dòng sau vào tôi applicationDidFinishLaunching

// Registers this class as the delegate of the audio session. 
[[AVAudioSession sharedInstance] setDelegate: self];  
// Allow the app sound to continue to play when the screen is locked. 
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; 
+0

Điều đó không có tác dụng đối với tôi, tôi phải làm rối tung những thứ nền ở đâu đó trong mã. Điều duy nhất tôi có thể nghĩ là tôi có NSNotificationCenter đang chạy để kiểm tra các trạng thái khác nhau của ứng dụng. Tôi không làm bất cứ điều gì với họ atm, chỉ cần đọc các tiểu bang khác nhau. –

+0

Những gì tôi phải làm, rằng tôi không tìm thấy bất cứ thứ gì trên mạng nêu rõ điều này, là đăng ký âm thanh của tôi cho AVAudioSession như đang hoạt động, như sau: [[AVAudioSession sharedInstance] setActive: YES error: NULL]; –

+0

Vì vậy, nó hoạt động với '[[AVAudioSession sharedInstance] setActive: YES error: NULL];'? Thú vị để biết, sẽ nhớ rằng trong tương lai :) – atomoil

1

Bạn có một ví dụ điển hình của một ứng dụng nền GPS đóng âm thanh ngay cả khi ở chế độ nền:

http://www.informit.com/articles/article.aspx?p=1646438&seqNum=5

Trong ví dụ này, AudioToolbox là đã sử dụng.

Tôi đã làm một thử nghiệm bản thân mình và nó hoạt động: tạo một dự án đơn giản mà theo dõi các bài GPS (location), và mỗi x nhận vị trí, chơi một âm thanh sử dụng

AudioServicesPlaySystemSound(soundId);

Sau đó, nếu bạn đặt audio là một phần của số của bạn và âm thanh sẽ được phát, ngay cả khi ứng dụng không ở trong nền trước nữa.

Tôi đã thực hiện một thử nghiệm và nó hoạt động tốt!

(tôi đã không quản lý để có được nó làm việc với AVPlayer vì vậy tôi fallbacked để AudioToolbox)

23

CẬP NHẬT IOS 11,2 với Swift 4:

Bây giờ nếu bạn đang sử dụng AVPlayer để chơi nhạc các tệp bạn cũng nên định cấu hình MPNowPlayingInfoCenter.default() để hiển thị thông tin đang phát trên màn hình khóa.

Dưới đây mã sẽ hiển thị bây giờ phát các điều khiển trên màn hình nhưng nó sẽ không thể trả lời bất kỳ lệnh nào.

Nếu bạn cũng muốn điều khiển để làm việc bạn nên kiểm tra dự án mẫu táo ở đây: https://developer.apple.com/library/content/samplecode/MPRemoteCommandSample/Introduction/Intro.html#//apple_ref/doc/uid/TP40017322

của Apple mẫu mã bao gồm tất cả nhưng tôi thấy nó khó hiểu.

Nếu bạn muốn phát âm thanh và hiển thị các điều khiển trên màn hình khóa, các bước này sẽ hoạt động tốt.

LƯU Ý QUAN TRỌNG: Nếu bạn là KHÔNG sử dụng AVPlayer để chơi âm thanh. Nếu bạn đang sử dụng một số thư viện của bên thứ ba để tạo âm thanh hoặc phát lại tệp âm thanh, bạn nên đọc các nhận xét bên trong mã. Ngoài ra nếu bạn đang sử dụng ios giả lập 11,2, bạn sẽ không thể nhìn thấy bất kỳ điều khiển trên màn hình khóa. Bạn nên sử dụng một thiết bị để xem nó hoạt động.


1- Chọn dự án -> capabilites -> thiết lập chế độ nền ON -> đánh dấu Audio, AirPlay và Picture in Picture

ios 11 background audio setting

2- AppDelegate.swift tập tin sẽ giống như thế này:

import UIKit 

import AVFoundation 

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate 
{ 

    var window: UIWindow? 

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool 
    { 
     // Override point for customization after application launch. 

     do 
     { 
      try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) 
      try AVAudioSession.sharedInstance().setActive(true) 

     //!! IMPORTANT !! 
     /* 
     If you're using 3rd party libraries to play sound or generate sound you should 
     set sample rate manually here. 
     Otherwise you wont be able to hear any sound when you lock screen 
     */ 
      //try AVAudioSession.sharedInstance().setPreferredSampleRate(4096) 
     } 
     catch 
     { 
      print(error) 
     } 
     // This will enable to show nowplaying controls on lock screen 
     application.beginReceivingRemoteControlEvents() 

     return true 
    } 
} 

3- ViewController.swift nên xem xét như thế này:

import UIKit 

import AVFoundation 
import MediaPlayer 

class ViewController: UIViewController 
{ 

    var player : AVPlayer = AVPlayer() 

    override func viewDidLoad() 
    { 
     super.viewDidLoad() 


     let path = Bundle.main.path(forResource: "music", ofType: "mp3") 
     let url = URL(fileURLWithPath: path!) 

     // !! IMPORTANT !! 
     /* 
      If you are using 3rd party libraries to play sound 
      or generate sound you should always setNowPlayingInfo 
      before you create your player object. 

      right: 
      self.setNowPlayingInfo() 
      let notAVPlayer = SomePlayer() 

      wrong(You won't be able to see any controls on lock screen.): 
      let notAVPlayer = SomePlayer() 
      self.setNowPlayingInfo() 
     */ 

     self.setNowPlayingInfo() 
     self.player = AVPlayer(url: url) 

    } 


    func setNowPlayingInfo() 
    { 
     let nowPlayingInfoCenter = MPNowPlayingInfoCenter.default() 
     var nowPlayingInfo = nowPlayingInfoCenter.nowPlayingInfo ?? [String: Any]() 

     let title = "title" 
     let album = "album" 
     let artworkData = Data() 
     let image = UIImage(data: artworkData) ?? UIImage() 
     let artwork = MPMediaItemArtwork(boundsSize: image.size, requestHandler: { (_) -> UIImage in 
      return image 
     }) 

     nowPlayingInfo[MPMediaItemPropertyTitle] = title 
     nowPlayingInfo[MPMediaItemPropertyAlbumTitle] = album 
     nowPlayingInfo[MPMediaItemPropertyArtwork] = artwork 

     nowPlayingInfoCenter.nowPlayingInfo = nowPlayingInfo 
    } 

    @IBAction func startPlayingButtonPressed(_ sender: Any) 
    { 
     self.player.play() 
    } 

OLD ĐÁP IOS 8.2:

câu trả lời Patrick là hoàn toàn đúng đắn.

Nhưng tôi sẽ ghi những gì tôi làm cho ios 8.2:

tôi thêm info.plist chế độ nền cần ứng dụng của tôi như dưới đây:

enter image description here

Và trong tôi AppDelegate.h tôi thêm các mục nhập này:

#import <AVFoundation/AVFoundation.h> 
#import <AudioToolbox/AudioToolbox.h> 

Sau đó, trong AppDelegate.m tôi i viết didFinishLaunchingWithOptionsthis ứng dụng hệt như dưới đây:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 
    // Override point for customization after application launch. 

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; 

    return YES; 
} 

Bây giờ App giữ chơi nhạc ngay cả khi màn hình bị khóa :)

+1

hoạt động nhưng jyfi trong Swift và ios 8.4 tôi không cần phải nhập AudioToolbox – longbow

+0

dễ dàng nhất. Cảm ơn! –

3

iOS 9 Swift

Tất cả những gì bạn cần là thêm thông tin sau vào didFinishLaunchingWithOptions

của bạn
Các vấn đề liên quan