Playing a youtube video in Mpmovieplayer or Mpmusicplayer ios - iphone

I want to play a youtube video with Mpmovieplayer or Mpmusicplayer. I want to do this because i have a requirement to make the app keep playing the video in background mode and that is quite not possible in uiwebview. Kindly if you could answer keeping the background mode audio playing in mind. Thanks in advance :)

You can use MPMovieplayerviewcontroller & also it looks like default player of iPhone.
Here is my answer : how to play live streaming from url for a camera that broadcasting live
FOR BACKGROUND: For background play write below lines in ViewDidLoad method -
NSError *setCategoryErr = nil;
NSError *activationErr = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryErr];
[[AVAudioSession sharedInstance] setActive: YES error: &activationErr];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
And also make a small change in your info.plist like below image:

I successfully found a solution for the UIWebView, After see this hack https://gist.github.com/romainbriche/2308668
It's different on IO5/6 and IOS7.
The problem you will encounter will be to not stop the sound when the app enter in background.
We work on it here https://github.com/0xced/XCDYouTubeVideoPlayerViewController/issues/10#issuecomment-34252488
I found some solutions but not perfects.

Write Given Below code in didFinishLaunchingWithOptions
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
BOOL success = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
if (!success) { NSLog(#"Error"); } else {NSLog(#"Success");}
NSError *activationError = nil;
success = [audioSession setActive:YES error:&activationError];
if (!success) { NSLog(#"Error"); } else {NSLog(#"Success");}

Related

AVPlayer background issue

I have a problem with AVPlayer, when I tried to make the player working on the background, the iPhone 6.0 simulator works fine, but the sound on the real device disappears when the application goes to the background!
- (IBAction)RayaFM {
NSURL *URLA = [NSURL URLWithString:#"http://live.raya.fm:8032/;stream.mp3"];
self.player = [AVPlayer playerWithPlayerItem:[AVPlayerItem playerItemWithURL:URLA]];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
[self.player play];
newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
if (newTaskId != bgTaskId != UIBackgroundTaskInvalid)
[[UIApplication sharedApplication] endBackgroundTask: bgTaskId];
bgTaskId = newTaskId;
}
You also need to include the following in your -info.plist file:
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>
See http://developer.apple.com/library/ios/#qa/qa1668/_index.html

How to play an audio when home button clicked in iphone sdk

Now am developing an application in which the application will play the audio automatically when the home button is tapped (when entering the background mode), below is my code i've used. it works perfectly in simulator but not working in any of the devices (iPhone, iPad, iPod). please guide me to go further...
- (void)applicationDidEnterBackground:(UIApplication *)application {
AVAudioSession * session = [AVAudioSession sharedInstance];
[session setDelegate: self];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
[session setActive:YES error:nil];
NSURL * url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/%#.wav", [[NSBundle mainBundle] resourcePath], soundName]];
AVAudioPlayer * audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
audioPlayer.numberOfLoops = -1;
[audioPlayer setVolume:1.0];
[audioPlayer prepareToPlay];
[audioPlayer play];
}
- (void)applicationWillResignActive:(UIApplication *)application {
NSAssert(backgroundTask == UIBackgroundTaskInvalid, nil);
backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
[[UIApplication sharedApplication] endBackgroundTask:backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
}
I don't think you can do this, when the app is going into the background audio is muted thus the sound you play will nog be heard.
And this will be very annoying and should just not be done, also the simulator reacts differently than then a real iOS device.
An app can only play audio that has been started before entering background mode. Note that an app can play silent audio, but Apple has rejected apps that play a lot of silence.

AVAudioPlayer cannot play music with a NSTimer in background

I want to play music with an AVAudioPlayer using an NSTimer, but [player prepareToPlay] returns NO & doesn't play in the background.
Can somebody give me some idea?
Here's my code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:#selector(playMusic:) userInfo:nil repeats:NO];
[self.window makeKeyAndVisible];
return YES;
}
- (void)playMusic:(NSTimer *)timer{
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
NSString *fileName = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:#"Apologize.mp3"];
NSURL *fileUrl = [NSURL fileURLWithPath:fileName];
NSError *error;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error];
if ([player prepareToPlay]) {
[player play];
NSLog(#"start!");
}else{
NSLog(#"error msg :%#",error);
}
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
if ([[UIApplication sharedApplication] respondsToSelector:#selector(beginReceivingRemoteControlEvents)]){
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
UIBackgroundTaskIdentifier backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
// /* just fail if this happens. */
[[UIApplication sharedApplication] endBackgroundTask:backgroundTask];
}];
}
You need to do this init in the viewDidLoad :
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"test"
ofType:#"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL
error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
This is for the audio initialization. Here, with a MP3 named test, imported in the project.
Note that the beginReceivingRemoteControlEvents part is very important. Without it, you cannot start playing from background, just keep on listening to music already playing from foreground.
Now you need to listen to the event didEnterInBackGround (you could go with the applicationDidEnterBackground of your app delegate, but this way you can put the code in the class it belongs to):
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(didEnterBG:)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
And now in that didEnterBG method :
self.backgroundTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(backgroundWork) userInfo:nil repeats:YES];
[self.backgroundTimer fire];
Here i make this sound repeat every 10s for personal reasons, but do whatever you need.
Finally, the backgroundWork method :
- (void)backgroundWork{
[self.audioPlayer prepareToPlay];
[self.audioPlayer play];
}
Now your audio file is playing in background :-)
You should also note that your app need to have specific rights to keep doing jobs in background. You need to check the box under 'YourTarget' -> Capabilities -> Background Modes : Audio and AirPlay. Otherwise, the OS will terminate you app in a few minutes in real conditions (with no debugger or instrument).
before going to code. you need to tell the OS that you want permission to play music in background.
you can do that by setting a Key in your app's info.plist
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>
doing so, you will be able to play audio when app moves to background.
I have the same issue, but I found the solution from this post: http://developer.apple.com/library/ios/#qa/qa1668/_index.html
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
[audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
if (setCategoryError) { /* handle the error condition */ }
NSError *activationError = nil;
[audioSession setActive:YES error:&activationError];
if (activationError) { /* handle the error condition */ }

iphone background audio on/off

I have an application that can play audio while the application is in the background with the entry in the plist and everything work fine.
But I would like to give the option to the user to setup the background play on and off
I use this method to activate the player
moviePlayer.useApplicationAudioSession = YES;
[moviePlayer play];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:NULL];
[[AVAudioSession sharedInstance] setActive:YES error:NULL];
I would like to change this option on run time and without any interruptions to the audio play.
Any ideas if this can happen?
Thanks for your time
I will post the solution here to make it better
if (backgroundSwitch.on) {
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:NULL];
}else {
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:NULL];
}

How to record and play sound in iPhone app?

I tried using AVAudioSession and AVAudioPlayer to record and play sounds respectively but the sound volume is very low.
I tried putting volume value of AVAudioPlayer to 1.0 and more but didn't help much.
What could be my other options to record sound which can be loud enough to play back?
This code should be useful for you:
#import <AudioToolbox/AudioServices.h>
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
sizeof (audioRouteOverride),&audioRouteOverride);
It will increase volume. The functionality of the code is to convert the ordinary sound to speaker sound on ur iPhone. That's why kAudioSessionOverrideAudioRoute_Speaker is used.
Since iOS7 you can fix this issue directly with AVAudioSession
The overrideOutputAudioPort method does the same than AudioSessionSetProperty
NSError *setOverrideError;
NSError *setCategoryError;
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&setCategoryError];
if(setCategoryError){
NSLog(#"%#", [setCategoryError description]);
}
[session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&setOverrideError];
if(setOverrideError){
NSLog(#"%#", [setOverrideError description]);
}
Swift version :
import AVFoundation
var overrideError : NSError?
if AVAudioSession.sharedInstance().overrideOutputAudioPort(.Speaker, error: &error){
}else{
print("error in overrideOutputAudioPort " + overrideError!.localizedDescription)
}
Swift 2:
do {
try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker)
} catch {
}
The following code fixed this issue for me:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error: nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
UInt32 doChangeDefault = 1;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(doChangeDefault), &doChangeDefault);
MAN, try this.
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
if (![session setCategory:AVAudioSessionCategoryPlayback
withOptions:kAudioSessionOverrideAudioRoute_Speaker
error:&setCategoryError]) {
// handle error
}
NSError *error;
NSData * data = [NSData dataWithContentsOfURL:self.playlet.urlSound];
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:data fileTypeHint:#"aac" error:&error];
self.audioPlayer.delegate = self;
if (error)
NSLog(#"Error: %#",
[error localizedDescription]);
else
[_audioPlayer play];
just set this
[session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&setOverrideError];
It works for me.