I am using AVPlayer to play a live stream from the Internet using the following code :
NSString *u = #"http://192.192.192.192:8036";
NSURL *url = [NSURL URLWithString:u];
radiosound = [[AVPlayer alloc] initWithURL:url];
[radiosound play];
And I have one button play :
[radiosound play];
and Pause :
[radiosound pause];
My issue is that I want to use only one button Play/Pause, but when I am using this code
if (radiosound.isPlaying) {
[radiosound pause];
} else {
[radiosound play];
}
My app crashes, because AVPlayer doesn´t recognize "isPlaying".
Any tips?
AVPlayer doesn't have an isPlaying property. Use the rate property (0.0 means stopped, 1.0 playing).
if (radiosound.rate == 1.0) {
[radiosound pause];
} else {
[radiosound play];
}
You can look at the AVPlayer class reference here.
After some research I found out that when there is no network connection, AVPlayer still sets the rate to 1.0 after receiving a -play message.
Thus, I also check for the currentItem and modified my method like that:
-(BOOL)isPlaying
{
if (self.player.currentItem && self.player.rate != 0)
{
return YES;
}
return NO;
}
Please share your opinion if you think something is wrong with this approach.
Related
I am working on this iOS app that plays music from URLs. Currently it has no issues playing through a playlist while the app is foregrounded, backgrounded, or even when the screen is locked ONLY IF the app was in the foreground prior to locking.
If the app is backgrounded THEN has the screen locked, the next song will load, but it will not play.
My question is: How can I get the AVPlayer to play the next song in a list while the app is in the background and the screen is locked?
Below is the code I am using to load and play the songs...
- (void)loadNextSong {
if (self.playlistIndex < self.playlist.count-1) { //check to see if the next track is in bounds of the playlist array
self.playlistIndex++;
[self.player pause];
[self serviceDidFetchSong:self.playlist[self.playlistIndex]];
[self.player play];
} else { //play the first song if we reach the end of the playlist
self.playlistIndex = 0;
[self.player pause];
[self serviceDidFetchSong:self.playlist[self.playlistIndex]];
[self.player play];
}
}
- (void)serviceDidFetchSong:(Song *)song {
if (song.audioFileURL != nil) {
if (![self.song.audioFileURL isEqual:song.audioFileURL]) {
if (self.timeIntervalObserver) {
[self.player removeTimeObserver:self.timeIntervalObserver];
}
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:song.audioFileURL options:0];
AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithAsset:asset];
self.player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
//this is just for a visual of the song progress
__block __weak SongPlayerViewController *blockSelf = self;
self.timeIntervalObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds((1.0f/5.0f), NSEC_PER_SEC)
queue:NULL
usingBlock:^(CMTime time){
[blockSelf updateProgressBar];
}];
}
self.song = song;
}
}
After trying to debug with some console logs and break points, I have verified that [self.player play] is definitely being called and that the correct URL is loaded each time.
My info.plist file has audio and fetch enabled for the required background modes.
The next song just doesn't seem to play at all when the app has been backgrounded and the screen is locked.
Any insight or suggestions would be much appreciated. Thank you.
EDIT
This seems to be an intermittent issue which appears much less frequently since the release of iOS 9.3 which leads me to believe this may have been related to the OS...?
It works when you play it twice.
player?.play()
player?.play()
I am very new to programming and I am just working on my first app. I haven't been able to find an answer to this for weeks. I would really appreciate some help.
I have background music through AVAudioPlayer (the only sound in my app) that begins playing when my app opens - here is the code in my appdelegate.m:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSString *bgmusic=[[NSBundle mainBundle]pathForResource:#"cloud_two-full-" ofType:#"mp3"];
bgmusic1=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:bgmusic] error:NULL];
bgmusic1.delegate=self;
bgmusic1.numberOfLoops=-1;
[bgmusic1 play];
[bgmusic1 setVolume:1.0];
}
So, I've created a uiswitch that I want to use to be able to mute the background music. Here is the IBAction in my viewcontroller.m:
- (IBAction)speakerOnOff:(id)sender {
static BOOL muted = NO;
if (muted) {
[bgmusic1 setVolume:1.0];
} else {
[bgmusic1 setVolume:0.0];
}
muted = !muted;
}
But when I click the switch to off the music continues to play at its normal volume. I only have 1 view controller. Please help! I just want the music to mute when the switch is clicked to off and then back to volume 1.0 when the switch is back on.
Write this code
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];
above
bgmusic1=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:bgmusic] error:NULL];
and make your button action like this
- (IBAction)speakerOnOff:(id)sender {
if ( bgmusic1.volume == 0) {
bgmusic1.volume = 1;
} else {
bgmusic1.volume =0;
}
}
In my application, I have one audio file. I want pause or stop the audio by clicking the button. I have tried with some code, but it still plays the audio. Please tell how to pause the audio or stop it by clicking the button.
Stop code.
- (IBAction)back:(id)sender {
[self.audioPlayer isPlaying];
[self.audioPlayer stop];
}
I have used the above to stop the playing audio but its not working.
where am I doing wrong? How to stop the audio?
Stopping Audio is easy just you need to take 2 Action Method for 2 separate buttons 1->Play and 2->Stop then code is as fallows
-(IBAction)Play:(id)sender
{
[self.audioPlayer play];
}
-(IBAction)Stop:(id)sender
{
[self.audioPlayer stop];
}
Another way is to use BOOL and use the 1 Action method to play and stop like this
First declare BOOl object
BOOL AudioBool;
-(IBAction)Audio:(id)sender
{
if(AudioBool == YES)
{
[self.audioPlayer play];
AudioBool = NO;
}
else
{
[self.audioPlayer stop];
AudioBool = YES;
}
}
I am starting to get convinced that iOS is just pure magic. I looked through numerous posts on AVAudioPlayer for solutions, but none worked.
When the application starts I have a movie starting off from MPMoviePlayerController and I have AVAudioPlayer kicking off with a sound as follows:
-(void)createAndPlayMovieFromURL:(NSURL *)movieURL sourceType:(MPMovieSourceType)sourceType{
/* Create a new movie player object. */
player = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
player.controlStyle = MPMovieControlModeDefault;
if (player)
{
/* Save the movie object. */
[self setMoviePlayerController:player];
/* Specify the URL that points to the movie file. */
[player setContentURL:movieURL];
/* If you specify the movie type before playing the movie it can result
in faster load times. */
[player setMovieSourceType:sourceType];
CGRect frame = CGRectMake(0, 0, 480, 320);
/* Inset the movie frame in the parent view frame. */
[[player view] setFrame:frame];
[player view].backgroundColor = [UIColor blackColor];
/* To present a movie in your application, incorporate the view contained
in a movie player’s view property into your application’s view hierarchy.
Be sure to size the frame correctly. */
[self.view addSubview: [player view]];
}
[[self moviePlayerController] play];
}
and for sound:
- (void)setupAudioPlayBack:(NSString *) path : (NSString *) extension{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:path
ofType:extension]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(#"Error in audioPlayer: %#",
[error localizedDescription]);
} else {
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
}
}
And now lets talk magic. When the first movie plays and the sound, the sound is not responding to either the volume controls on the phone nor to Silent Mode On switch.
But then immediately a second movie plays with its own sound and everything works fine - there is no sound with Silent Mode On, if Silent Mode Off it responds to Volume Controls. 3rd movie - plays perfectly too.
I tried using the player.useApplicationAudioSession = NO for MPMoviePlayerController - fixed the problem with the first time sound not responding to Silent Mode or Volume Controls, but now when the second movie starts to play it freezes instantly and the sound played is cut from the original size to something around 2 seconds.
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:nil]; didn't help either wherever I set it.
So my question is - how to make the MPMoviePlayerController interact with AVAudioPlayer without any problems...
Ok I actually found a solution (once again, magic).
When you start your ViewController you set it up as follows:
- (void)viewDidLoad
{
[self setupAudioPlayBack:#"sound1" :#"caf"];
[self playMovieFile:[self localMovieURL:#"mov1" :#"mov"]];
audioTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(playAudio) userInfo:nil repeats:NO];
[super viewDidLoad];
}
Where the playAudio method is simply:
- (void)playAudio{
[audioPlayer play];
}
Just 0.1 millisecond timer is enough to make everything work (0.0 doesn't work) and make sure a new video doesn't start before the audio finishes or it will destroy the settings so you will have to invalidate the timer and redo the timer again.
In my application I am using an AVAudioRecorder object to allow the user to record a sound file, and when the user is done recording they can play the sound via the AVAudioPlayer. The issue I'm having is when the user tries to play the audio file it only plays for one second. What is even more odd is that this code worked perfect on iOS 5, but since upgrading to iOS 6 this issue has started to happen.
I have checked the file that is being created via iTunes file sharing, and I'm able to play the entire sound file on my desktop.
Below I have pasted the code from my manipulation file that loads the audio player. From what I can tell the
- (void)playRecordingBtnClk:(id)sender
{
NSLog(#"Play btn clk");
if (!isRecording) {
// disable all buttons
[_recordButton disableButton];
[_stopButton disableButton];
[_playButton disableButton];
[_saveButton disableButton];
// create the player and play the file from the beginning
if (audioPlayer) {
[audioPlayer release];
audioPlayer = nil;
}
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioRecorder.url error:&error];
audioPlayer.delegate = self;
audioPlayer.currentTime = 0.0;
[audioPlayer prepareToPlay];
if (error) {
NSLog(#"Error Playing Audio File: %#", [error debugDescription]);
return;
}
[audioPlayer play];
[self startTicker];
}
}
It appears that the
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
method is being called after one second which is why the audio player stops. Anyone have any ideas what is going on here?
For iOS 6.0, add two more lines:
soundPlayer.currentTime = soundPlayer.duration + soundPlayer.duration;
soundPlayer.numberOfLoops = 1;
Not a perfect solution. We may need to wait for iOS 6.0.1/6.1 update.
For more, please visit this, someone commented there, saying it might be a problem of CDAudioManager.