AVPlayer Works on Simulator, but not on device - ios

playerItem=[AVPlayerItem playerItemWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.radio.com.lk/y-fm/"]]];
player=[AVPlayer playerWithPlayerItem:playerItem] ;
[player play];
It's working on Simulator but in the device, it's not. In the console,
I have the following error:
CredStore - performQuery - Error copying matching creds.
Error=-25300, query={
class = inet;
"m_Limit" = "m_LimitAll";
"r_Attributes" = 1;
sync = syna; }
Can anyone help me with a clue?

Please add below code in your app delegate. It may help you
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[AVAudioSession sharedInstance] setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&activationError];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionAllowBluetooth error:&setCategoryError];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}

My answer is for you
ViewController.h
#import <UIKit/UIKit.h>
#import <AVKit/AVKit.h>
#interface ViewController : UIViewController
#property (strong, nonatomic) AVPlayerViewController *playerViewController;
#property (nonatomic,strong)AVAudioPlayer *player;
- (IBAction)actionPlay:(id)sender;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize player;
#synthesize playerViewController;
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)actionPlay:(id)sender {
AVPlayerItem* playerItem = [AVPlayerItem playerItemWithURL:yourURL];
AVPlayer* playVideo = [[AVPlayer alloc] initWithPlayerItem:playerItem];
playerViewController = [[AVPlayerViewController alloc] init];
playerViewController.player = playVideo;
playerViewController.player.volume = 0;
playerViewController.view.frame = self.view.bounds;
[self.view addSubview:playerViewController.view];
[playVideo play];
}

Related

How to play .caf audio file from server url in ios

I try to play audio from server url but nothing play, But i try to play audio from document directory path url and it play fine.
NSData *songData=[NSData dataWithContentsOfURL:[NSURL URLWithString:
[NSString stringWithFormat:#"%#",aSongURL]]];
AVAudioPlayer *abc = [[AVAudioPlayer alloc] initWithData:songData error:nil];
abc.numberOfLoops=0;
[abc prepareToPlay];
[abc play];
You can try this. Hope it helps.
AVPlayer *objAVPlayer = [[AVPlayer alloc] initWithURL:url];
[objAVPlayer play];
My answer is below
ViewController.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#interface ViewController : UIViewController
#property (nonatomic,strong)AVAudioPlayer *player;
- (IBAction)actionPlayAudio:(id)sender;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize player;
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)actionPlayAudio:(id)sender {
NSString *strAudioFileURL = #"dev.epixelsoft.co/love_app/audio/img_14957068361.caf";
NSURL *soundFileURL = [NSURL fileURLWithPath:strAudioFileURL];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
[player play];
}

Objective-C: How to make AVPlayer keep playing in the background

I know that there are a lot questions like mine but nothing is working
for me.
I'm trying to let the AVPlayer keep playing when i exit the app, i have implemented the following Singleton Class :
.h file:
#import <AVFoundation/AVFoundation.h>
#import <Foundation/Foundation.h>
#interface LiveStreamSingleton : NSObject<AVAudioPlayerDelegate>{
}
+(LiveStreamSingleton *)sharedInstance;
-(void)playStream;
-(void)stopStream;
-(bool)status;
#end
.m file:
#import "LiveStreamSingleton.h"
static LiveStreamSingleton *sharedInstance = nil;
#interface LiveStreamSingleton (){
AVPlayer *audioPlayer;
}
#end
#implementation LiveStreamSingleton
+ (LiveStreamSingleton*) sharedInstance {
static dispatch_once_t _singletonPredicate;
static LiveStreamSingleton *_singleton = nil;
dispatch_once(&_singletonPredicate, ^{
_singleton = [[super allocWithZone:nil] init];
});
return _singleton;
}
+ (id) allocWithZone:(NSZone *)zone {
return [self sharedInstance];
}
-(void)playStream{
//NSError *error = nil;
NSURL *urlStream;
NSString *urlAddress = #"http://198.178.123.23:8662/stream/1/;listen.mp3";
urlStream = [[NSURL alloc] initWithString:urlAddress];
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:urlStream options:nil];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:avAsset];
audioPlayer = [AVPlayer playerWithPlayerItem:playerItem];
//This enables background music playing
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
audioPlayer = [AVPlayer playerWithURL:urlStream];
if(!audioPlayer.error){
NSLog(#"Trying to play from singleton!");
[audioPlayer play];
NSLog(#"rate: %f",audioPlayer.rate);
}
}
-(void)stopStream{
NSLog(#"Trying to stop from singleton!");
[audioPlayer pause];
}
-(bool)status{
bool stat;
if(audioPlayer.rate > 0){
stat = true;
}else{
stat = false;
}
return stat;
}
#end
I have set the [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; for playing in the background, but i tried it on my real ipad, it's not working.
Any ideas?
add a key named Required background modes in property list (.plist) file ..
as following picture..
and add following code in
Objective-C
AppDelegate.h
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
AppDelegate.m
in application didFinishLaunchingWithOptions
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
Swift
import AVFoundation
import AudioToolbox
class AppDelegate: UIResponder, UIApplicationDelegate
{
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
}
catch {
}
}
}
Hope it helps.

How to play m3u audio stream in iOS app

I'm trying to create an iOS/iPhone radio app using Xcode 4.5.2.
I wanted to stream #"http://xx.xxxxxxx.com/8111/radio.m3u" with play, pause, volume control and able to play on background feature/multitasking.
I've added AVFoundation, Mediaplayer and AudioToolBox frameworks thus far. I've added play, pause and slider objects to xib.
ViewController.h
#interface ViewController : UIViewController
#property (strong,nonatomic) MPMoviePlayerController *myPlayer;
#property (weak, nonatomic) IBOutlet UISlider *myslider;
- (IBAction)playButtonPressed;
- (IBAction)myslider:(id)sender;
#end
ViewController.m
#import "ViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#interface ViewController ()
{
UISlider *volumeSlider;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
}
- (IBAction)playButtonPressed;
{
NSString *urlAddress = #"http://xxxxxxx.com/8111/listen.m3u";
NSURL *url = [NSURL URLWithString:urlAddress];
MPMoviePlayerController *player = [[MPMoviePlayerController alloc]initWithContentURL:url];
player.movieSourceType = MPMovieSourceTypeStreaming;
[player prepareToPlay];
self.myPlayer = player;
[self.view addSubview:self.myPlayer.view];
[self.myPlayer play];
}
- (IBAction)stopButtonPressed;
{
[self.myPlayer stop];
}
- (IBAction)myslider:(id)sender
{
MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame: CGRectMake(10, 10, 200, 40)];
[volumeSlider addSubview:volumeView];
[volumeView sizeToFit];
}
There are Two way to achieve this.
You can directly load you URL in UIWebView and it will properly.
You can also use MPMoviePlayerController.
Create a "MPMoviePlayerController *player" as a strong object in your ViewController.
So you code would look something like below:
#interface ViewController ()
{
UISlider *volumeSlider;
MPMoviePlayerController *player;
}
#end
- (IBAction)playButtonPressed;
{
NSString *urlAddress = #"http://xxxxxxx.com/8111/listen.m3u";
NSURL *url = [NSURL URLWithString:urlAddress];
if(nil != player)
{
player = nil; // Alternatively you can stop and restart with the different stream.
}
player = [[MPMoviePlayerController alloc]initWithContentURL:url];
player.movieSourceType = MPMovieSourceTypeStreaming;
[player prepareToPlay];
self.myPlayer = player;
[self.view addSubview:self.myPlayer.view];
[self.myPlayer play];
}

Stop background music

I have this app that has several view controllers. In the app delegate, I set it so that as soon as the app finishes launching, the background music starts. However, on another view controller, I have this button that plays this video. My problem is that when I play the movie, the background audio overlaps with the movie. My question is, how do I stop the music when I play the movie and play the music after the movie ends.
Here is my app_delegate.h:
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#interface App_Delegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
UINavigationController *navigationController;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
#end
Here is my App_Delegate.m
#import "App_Delegate.h"
#import "RootViewController.h"
#implementation App_Delegate
#synthesize window;
#synthesize navigationController;
#pragma mark -
#pragma mark Application lifecycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
{NSString* soundFilePath = [[NSBundle mainBundle] pathForResource:#"beethoven_sym_5_i" ofType:#"mp3"];
NSURL* soundFileURL = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops=-1;
[player play];
}
// Override point for customization after application launch.
// Set the navigation controller as the window's root view controller and display.
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
return YES;
}
- (void)dealloc {
[navigationController release];
[window release];
[super dealloc];
}
#end
My MovieViewController.h:
#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#interface MovieViewController : UIViewController {
IBOutlet UIScrollView *sesamescroller;
}
- (IBAction)playsesamemovie:(id)sender;
#end
Finally, my MovieViewController.m
#import "MovieViewController.h"
#interface MovieViewController ()
#end
#implementation MovieViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
- (void)viewDidUnload
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)playsesamemovie:(id)sender {
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"How to make Sesame chicken" ofType:#"mp4"];
NSURL *fileURL = [NSURL fileURLWithPath:filepath];
MPMoviePlayerController *moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlaybackComplete:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:moviePlayerController];
[self.view addSubview:moviePlayerController.view];
moviePlayerController.fullscreen = YES;
[moviePlayerController play];
}
- (void)moviePlaybackComplete:(NSNotification *)notification
{
MPMoviePlayerController *moviePlayerController = [notification object];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:moviePlayerController];
[moviePlayerController.view removeFromSuperview];
[moviePlayerController release];
}
- (void)dealloc {
[sesamescroller release];
[super dealloc];
}
#end
The code you show has a local variable pointing to the player object. To control the player, other code needs to be able to find it. Like this:
In App_Delegate.h:
#property (strong) AVAudioPlayer *player;
in App_Delegate.m: (where did this underbar come from? Most unconventional!)
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
self.player.numberOfLoops=-1;
[self.player play];
Then, wherever you want to control it:
[((App_Delegate *)([UIApplication sharedApplication].delegate)).player pause];
// ...
[((App_Delegate *)([UIApplication sharedApplication].delegate)).player play];
set scalling mode to your player
for Paused :
[moviePlayerController setScalingMode:MPMoviePlaybackStatePaused];
for Stopped:
[moviePlayerController setScalingMode:MPMoviePlaybackStateStopped];
If possible on iOS, you can use scriptable feature to send message to mute. I did this sometime back for Mac OS X where I used to control iTunes from another app.
First add start to songs in application delegate
.h application delegate
#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#class ViewController;
#interface AppDelegate : UIResponder <UIApplicationDelegate,AVAudioPlayerDelegate>
{
AVAudioPlayer *myAudioPlayer;
NSDictionary *config;
NSMutableArray *ARRAY;
}
-(void)stop;
#property(retain,nonatomic) NSDictionary *config;
#property (nonatomic, retain) AVAudioPlayer *myAudioPlayer;
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) ViewController *viewController;
#end
.m application delegate
#implementation AppDelegate
{
AVAudioPlayer* audioPlayer;
}
#synthesize myAudioPlayer;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions
{
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
audioPlayer.delegate = self;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
audioPlayer.numberOfLoops = 1;
audioPlayer.delegate=self;
[audioPlayer play];
}
-(void)stop
{
[audioPlayer stop];
}
-(void)star
{
[audioPlayer play];
}
when use required start and stop background music in application
directly call this method -start and -stop
..it really work

Playing a Sound While App Runs

EDITED
still not sure whats wrong please help
hi there I'm creating and iOS application and trying to make it play a sound when running I've type up my code in the app delegate .h , .m and it plays the sound fine but the thing is it goes to a black screen when my ViewController.xib has a blue background heres heres the code i have
AppDelegate.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#class ViewController;
#interface AppDelegate : NSObject <UIApplicationDelegate, AVAudioPlayerDelegate> {
UIWindow *window;
ViewController *viewController;
AVAudioPlayer *_backgroundMusicPlayer;
BOOL _backgroundMusicPlaying;
BOOL _backgroundMusicInterrupted;
UInt32 _otherMusicIsPlaying;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet ViewController *viewController;
- (void)tryPlayMusic;
AppDelegate.m
#import "AppDelegate.h"
#import "ViewController.h"
#implementation AppDelegate
#synthesize window = _window;
#synthesize viewController = _viewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Set up the audio session
// See handy chart on pg. 55 of the Audio Session Programming Guide for what the categories mean
// Not absolutely required in this example, but good to get into the habit of doing
// See pg. 11 of Audio Session Programming Guide for "Why a Default Session Usually Isn't What You Want"
NSError *setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&setCategoryError];
// Create audio player with background music
NSString *ticktockPath = [[NSBundle mainBundle] pathForResource:#"ticktock" ofType:#"wav"];
NSURL *ticktockURL = [NSURL fileURLWithPath:ticktockPath];
NSError *error;
_backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:ticktockURL error:&error];
[_backgroundMusicPlayer setDelegate:self]; // We need this so we can restart after interruptions
[_backgroundMusicPlayer setNumberOfLoops:-1]; // Negative number means loop forever
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
- (void) audioPlayerBeginInterruption: (AVAudioPlayer *) player {
_backgroundMusicInterrupted = YES;
_backgroundMusicPlaying = NO;
}
- (void) audioPlayerEndInterruption: (AVAudioPlayer *) player {
if (_backgroundMusicInterrupted) {
[self tryPlayMusic];
_backgroundMusicInterrupted = NO;
}
}
- (void)applicationDidBecomeActive:(NSNotification *)notification {
[self tryPlayMusic];
}
- (void)tryPlayMusic {
// Play the music if no other music is playing and we aren't playing already
if (_otherMusicIsPlaying != 1 && !_backgroundMusicPlaying) {
[_backgroundMusicPlayer prepareToPlay];
[_backgroundMusicPlayer play];
_backgroundMusicPlaying = YES;
}
}
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
#end
ok so thats all the code
and heres what i get when app loads and the sound works fine
and this is what i want to get (ViewController.xib)
Thank in advanced
- (void)applicationDidFinishLaunching:(UIApplication *)application {
NSError *setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&setCategoryError];
self.viewController = [[ViewController alloc] init];
// Create audio player with background music
NSString *ticktockPath = [[NSBundle mainBundle] pathForResource:#"ticktock" ofType:#"wav"];
NSURL *ticktockURL = [NSURL fileURLWithPath:ticktockPath];
NSError *error;
_backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:ticktockURL error:&error];
[_backgroundMusicPlayer setDelegate:self]; // We need this so we can restart after interruptions
[_backgroundMusicPlayer setNumberOfLoops:-1]; // Negative number means loop forever
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
new code
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.viewController = [[[ViewController alloc] initWithNibName:#"ViewController" bundle:nil] autorelease];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
You never initialized your view controller.
Somewhere before you do
[window addSubview:viewController.view];
You need to do
self.viewController = [[ViewController alloc] init];
I see that you declared the property as an IBOutlet.. is it actually hooked up to something in Interface Builder?
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
NSError *setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&setCategoryError];
// Create audio player with background music
NSString *ticktockPath = [[NSBundle mainBundle] pathForResource:#"ticktock" ofType:#"wav"];
NSURL *ticktockURL = [NSURL fileURLWithPath:ticktockPath];
NSError *error;
_backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:ticktockURL error:&error];
[_backgroundMusicPlayer setDelegate:self]; // We need this so we can restart after interruptions
[_backgroundMusicPlayer setNumberOfLoops:-1]; // Negative number means loop forever
self.viewController = [[[ViewController alloc] initWithNibName:#"ViewController" bundle:nil] autorelease];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
Copy that function and just delete this one - (void)applicationDidFinishLaunching:(UIApplication *)application completely.
You should also consider converting your project to use ARC. It will remove the need to retain/release/autorelease statements.
You have two targets - are all your resources included in the target that you're building?

Resources