Control volume of one channel in objective-c - ios

I have an really simple audio player with AVAudioPlayer with (at this point) one song.
It is simple to control the volume of both channels (left and right) at the same time.
But is it possible to control only the left channel or only the right channel?
In this way I can set the left speaker a little louder then the right or vice versa.

The AVAudioPlayer reference should be consulted to answer this question.
You can see from the interface that you can't control the left/right channel directly, but you can set the pan from -1 (full left) to 1 (full right). Perhaps this will achieve what you are looking for?
Using core audio will be much more difficult, but it should be able to handle this. Another possibility using AVAudioPlayer is to split the sound into its separate channels and to play them separately. Then, you can set the volume separately. There is an example in the documentation of how to ensure that two sounds play at exactly the same time. (And, you'll want to set the pan for each sound separately so that each sound plays correctly.)
A less efficient method is two play two copies of the .mp3 at once. (Caveat: I haven't tested this code.)
// assumes you have url for the file you want to play
AVAudioPlayer *first = [[AVAudioPlayer alloc] initWithContentsOfURL:myUrl error:nil];
AVAudioPlayer *second = [[AVAudioPlayer alloc] initWithContentsOfURL:myUrl error:nil];
first.pan = -1; // only play on left channel
second.pan = 1; // only play on right channel
first.volume = 0.6;
second.volume = 1.0;
NSTimeInterval shortStartDelay = 0.01;
NSTimeInterval now = player.deviceCurrentTime;
[first playAtTime: now + shortStartDelay];
[second playAtTime: now + shortStartDelay];

Related

NSTimer not passing parameters correctly?

I have a UITableViewCell. It has 2 AVPlayers, 2 AVPlayerItems, and 2 AVPlayerLayers. One AVPlayer and its contents are on the right side of the cell, and one on the left side of the cell. I am using the AVAssetResourceLoader to cache and play videos at the same time. This works great, except the second video does not display. It does cache properly, because after scrolling the tableview, it plays correctly as it should from the cache. But just the AVPlayerLayer does not display the video content as it should.
The AVAssetResourceLoader can not handle 2 simultaneous downloads. Upon first loading the tableview, the video on the left starts to download/play. The code for playing the video on the right side is read immediately after the code for downloading/playing the video on the left side--meaning of course, that the download process has not yet finished. To fix this problem, I have created a timer, like so:
if (self.downloadInProgress) {
// download is in progress. wait to start next download
self.downloadQueueCount++;
NSDictionary *videoSettings = #{#"id": activity2.objectId,
#"activity": activity2, #"cell": videoCell, #"left": #NO}
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.2
target:self selector:#selector(DownloadNextVideo:)
userInfo:videoSettings repeats:YES];
} else {
[self playStreamingVideoOnRightInCell:videoCell withActivity:activity2];
}
And then the selector method:
- (void)DownloadNextVideo:(NSTimer *)timer {
if (self.downloadInProgress == NO) {
NSString *activityId = [[timer userInfo] objectForKey:#"id"];
self.videoChallengeID1 = activityId;
CompletedTableViewCell *videoCell = (CompletedTableViewCell *)[[timer userInfo]objectForKey:#"cell"];
Activity *activity = [[timer userInfo] objectForKey:#"activity"];
BOOL left = [[timer userInfo] objectForKey:#"left"];
[self.timer invalidate];
if (left) {
[self playStreamingVideoOnLeftInCell:videoCell withActivity:activity];
} else {
[self playStreamingVideoOnRightInCell:videoCell withActivity:activity];
}
}
}
Basically, this works correctly--the AVAssetResourceLoader gets the correct URL, correct activityID, and downloads/caches the correct video--except the video does not play as it downloads. I changed background colors, and I can confirm that the AVPlayerLayer is indeed present in the frame it should be. Just no video shows up.
I tried switching left and right videos and download order--and in that case, the right video played, and the left video didn't play. Basically, whichever video has to use this timer and continually check if a download is in progress or not, is the video that does not display correctly, and that makes me think it is something I am doing wrong with the timer concerning scope/passing variables.
One last detail, in case it may help. If I say the following (instead of the first method I had here):
if (self.downloadInProgress) {
[self playStreamingVideoOnRightInCell:videoCell withActivity:activity2];
}
Then, the playerLayer DOES show video--but it's the wrong video. It shows the same video as in the left side of the cell.
This has been a nightmare to debug, and I am fairly certain at this point that it has something to do with using a timer here to play the video instead of doing it inside the regular scope. Anyone have any ideas what I could be doing wrong?
In order to fix the proper video playing, you need to change the following. You are using the NSNumber value instead of a BOOL for the left value.
Your code:
BOOL left = [[timer userInfo] objectForKey:#"left"];
Should be:
BOOL left = [[[timer userInfo] objectForKey:#"left"] boolValue];

How to Speed up the audio Playing in MpMoviePlayerController

I am using MPMoviePlayerController in my app to play the video and audios. I want to give an option to user to play the audio/video slower/faster then the normal speed i.e 0.5x (slower then normal ), 1x (normal speed), 2x (double speed then normal.).
I want to know is there any way that i can speed up/down the MPMoviePlayerController streaming so that user can have options to listen/view the audio/video at slower/faster speed.
i found the solution to this problem myself.
When you use MPMoviePlayerController and make its instance then you have a property of MpMoviePlayerController as currentPlaybackRate. It is set to 1.0 by default means normal playing. If you sets its value to 1.5 or 2.0 then it will play the currently playing audio at that speed.
See the following code.
MPMoviePlayerController *moviePlayer = [MPMoviePlayerController alloc]init];
moviePlayer.movieSourceType = MPMovieSourceTypeStreaming;
moviePlayer.contentURL = #"http://someduumyUrl.com" ;
moviePlayer.controlStyle = MPMovieControlStyleDefault;
[moviePlayer prepareToPlay];
moviePlayer.currentPlaybackRate = 2.0 // will play the audio at double speed.

iOS 7 rewind songs on lock screen using AVPlayer

I havn't found the way how to rewind song from lock screen iOS 7. Volume slider is available, all the buttons work correctly but the upper slider is not available!
AVPlayer is the class I'm using.
Any help is appreciated!
You'll need to set this in the "now-playing info".
Whenever the item (track) changes, do something like
NSMutableDictionary *nowPlayingInfo = [[NSMutableDictionary alloc] init];
[nowPlayingInfo setObject:track.artistName forKey:MPMediaItemPropertyArtist];
[nowPlayingInfo setObject:track.trackTitle forKey:MPMediaItemPropertyTitle];
...
[nowPlayingInfo setObject:[NSNumber numberWithDouble:self.player.rate] forKey:MPNowPlayingInfoPropertyPlaybackRate];
[nowPlayingInfo setObject:[NSNumber numberWithDouble:self.currentPlaybackTime] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
[MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = nowPlayingInfo;
Whenever the playback rate changes (play/pause), do
NSMutableDictionary *nowPlayingInfo = [[MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo mutableCopy];
[nowPlayingInfo setObject:[NSNumber numberWithDouble:self.player.rate] forKey:MPNowPlayingInfoPropertyPlaybackRate];
[nowPlayingInfo setObject:[NSNumber numberWithDouble:self.currentPlaybackTime] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
[MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = nowPlayingInfo;
You can get the current playback time like this:
- (NSTimeInterval)currentPlaybackTime {
CMTime time = self.player.currentTime;
if (CMTIME_IS_VALID(time)) {
return time.value / time.timescale;
}
return 0;
}
You have to register for different events like below in swift
MPRemoteCommandCenter.shared().playCommand.addTarget(self, action: #selector(self.handleRemoteCommandActions))
MPRemoteCommandCenter.shared().nextTrackCommand.addTarget(self, action: #selector(self.handleRemoteCommandActions))
MPRemoteCommandCenter.shared().previousTrackCommand.addTarget(self, action: #selector(self.handleRemoteCommandActions))
MPRemoteCommandCenter.shared().stopCommand.addTarget(self, action: #selector(self.handleRemoteCommandActions))
MPRemoteCommandCenter.shared().pauseCommand.addTarget(self, action: #selector(self.handleRemoteCommandActions))
MPRemoteCommandCenter.shared().changePlaybackPositionCommand.isEnabled = true
MPRemoteCommandCenter.shared().changePlaybackPositionCommand.addTarget(self, action: #selector(self.handleChangePlaybackPositionRemoteCommandActions))
let rcc = MPRemoteCommandCenter.shared()
let skipBackwardIntervalCommand: MPSkipIntervalCommand? = rcc.skipBackwardCommand
skipBackwardIntervalCommand?.isEnabled = false
let skipForwardIntervalCommand: MPSkipIntervalCommand? = rcc.skipForwardCommand
skipForwardIntervalCommand?.isEnabled = false
let seekForwardCommand: MPRemoteCommand? = rcc.seekForwardCommand
seekForwardCommand?.isEnabled = true
rcc.changePlaybackPositionCommand.isEnabled = true
rcc.changePlaybackRateCommand.isEnabled = true
rcc.ratingCommand.isEnabled = true
rcc.playCommand.isEnabled = true
rcc.togglePlayPauseCommand.isEnabled = true
here handleChangePlaybackPositionRemoteCommandActions this method will be your method which will have to manage seeking of song when scrubber (upper slider) changes its value
it will look something like below:-
#objc func handleChangePlaybackPositionRemoteCommandActions(event:MPChangePlaybackPositionCommandEvent) -> MPRemoteCommandHandlerStatus
{
print("handleChangePlaybackPositionRemoteCommandActions : \(event.positionTime)")
self.appDelegate.audioPlayer?.seek(to: CMTime(seconds: event.positionTime, preferredTimescale: (self.appDelegate.audioPlayer?.currentItem?.currentTime().timescale)!))
MPNowPlayingInfoCenter.default().nowPlayingInfo![MPNowPlayingInfoPropertyElapsedPlaybackTime] = event.positionTime
return MPRemoteCommandHandlerStatus.success
}
I can not seem to find a way to add the functionality of dragging the progress bar to scrub through the currently playing song either, however getting the progress bar to show is partly covered by Chris above, but you have to pass the song's duration in as well as the other information to get the progress bar to show up. So in addition to what Chris pointed out, you need to add the following to the NSMutableDictionary:
[nowPlayingInfo setObject:[track valueForProperty: MPMediaItemPropertyPlaybackDuration]
forKey:MPMediaItemPropertyPlaybackDuration];
Also, you can handle a long press of the forward and back buttons and scroll your music. In the:
- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent
you can look for these event subtypes:
if (receivedEvent.subtype == UIEventSubtypeRemoteControlBeginSeekingBackward){};
if (receivedEvent.subtype == UIEventSubtypeRemoteControlBeginSeekingForward){};
if (receivedEvent.subtype == UIEventSubtypeRemoteControlEndSeekingBackward){};
if (receivedEvent.subtype == UIEventSubtypeRemoteControlEndSeekingForward){};
The BeginSeekingForward and BeginSeekingBackward are triggered by long presses of the forward and back buttons respectively, and of course the EndSeekingForward and EndSeekingBackward event subtypes are when the finger is lifted off the button.
When you get these event subtypes, pass a new NSDictionary to
[MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo
with all of the information that was already in it (otherwise properties that you do not pass in will be cleared) plus a new MPNowPlayingInfoPropertyElapsedPlaybackTime and MPNowPlayingInfoPropertyPlaybackRate. For the rate, you decide how fast you want to scroll the audio. 1 is normal speed, negative values play backwards, so -2 is 2x normal speed in reverse. You will have to set the playback rate of the MPNowPlayingInfoCenter to be the same as the playback rate of the AVPlayer or they will not line up. This is why you want to also pass in the current time. You can get this with:
[player currentTime]
so to set the current time and rate:
[nowPlayingInfo setObject:[player currentTime]
forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
[nowPlayingInfo setObject:[[NSNumber alloc] initWithFloat:10]
forKey:MPNowPlayingInfoPropertyPlaybackRate];
and set the rate of the player with:
[player setRate:10]
This should line up both the player and the progress bar while scrolling with a 10x forward scroll speed. So you would do this when you get the BeginSeekingForward event subtype. When the scrolling ends, set the rate back to one, but still pass in the time and other information to the information center. For BeginSeekingBackward, just use a negative number for the rate.
I know this is an old post, but there was not a good solution and I ran across this thread while searching for how to get music information on to the lock screen. I was trying to implement this functionality in C# with Xamarin iOS and found a nice guide and sample Objective-C app with some of this functionality at http://www.sagorin.org/ios-playing-audio-in-background-audio/. But it did not have the scrolling functionality, nor did it make use of the information center, it just covered handling pause/play from the lock screen. I made a sample app in C# with Xamarin that demonstrates supplying info to the information center and scrolling with the back and forward buttons from the lock and control screens, which you can get here: https://github.com/jgold6/Xamarin-iOS-LockScreenAudio
I hope someone finds this helpful.
Here's how you do this thing with the timeline slider:
First of all the nowPlayingInfo must be set right. You can find how to do that anywhere (don't forget the key MPNowPlayingInfoPropertyPlaybackRate);
Second is to define the action for 'sliding':
MPChangePlaybackPositionCommand *changePlaybackPositionCommand = [[MPRemoteCommandCenter sharedCommandCenter] changePlaybackPositionCommand];
[changePlaybackPositionCommand addTarget:self action:#selector(changePlaybackPositionEvent:)];
[[MPRemoteCommandCenter sharedCommandCenter].changePlaybackPositionCommand setEnabled:YES];
Inside the action you can do some additional things, but the main thing here is
[yourPlayer seekTo:event.positionTime completionHandler:^(BOOL finished) {
[self updatePlaybackRateMetadata];
}];
updatePlaybackRateMetadata method has to update MPNowPlayingInfoPropertyElapsedPlaybackTime and MPNowPlayingInfoPropertyPlaybackRate.
A lot of time passed, but i hope this will help someone!

UISlider and playing sound in iOS

I'm trying to use a UISlider to play sound in a fashion which emulates how a violin bow would play on a string. At current, I can get sound playing from the slider however the functionality isn't correct.
-(IBAction) slider
{
NSString* path = [[NSBundle mainBundle] pathForResource:#"im_on" ofType:#"mp3" ];
if (song) [song release];
song = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[song play];
}
This is code and there is not much else to it. I have linked this method in IB to a slider which is triggered on the event Value Changed. When set to continuous = YES, when the slider begins to slide, the sound plays. However if it continues to slide the sound will stop until the slider stops where it then play again. When set to continuous = NO, the sound does not play when the value changes but when the touch is lifted. the sound continues to play while the value is hanging after that.
Is there a way to have the sound continue to play until the slider stops/changes direction/touch is released? i.e override all but the first value changed sent event until x condition is met.

How do I loop a video with AVFoundation without unwanted pauses at the end?

I am trying to play a video clip that loops indefinitely. I am doing this the way Apple recommends; by setting up a notification that gets triggered by AVPlayerItemDidPlayToEndTimeNotification:
#property(nonatomic) AVPlayer *videoPlayer;
#property(nonatomic) AVPlayerItem *videoPlayerItem;
-(void)loadVideo
{
NSURL *url = [[NSBundle mainBundle] URLForResource:filename withExtension:extension];
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
NSString *tracksKey = #"tracks";
[asset loadValuesAsynchronouslyForKeys:#[tracksKey] completionHandler:
^{
dispatch_async(dispatch_get_main_queue(),
^{
NSError *error;
AVKeyValueStatus status = [asset statusOfValueForKey:tracksKey error:&error];
if (status == AVKeyValueStatusLoaded)
{
[self setVideoPlayerItem:[AVPlayerItem playerItemWithAsset:asset]];
[videoPlayerItem addObserver:self forKeyPath:#"status" options:0 context:&ItemStatusContext];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector (videoPlayerItemDidReachEnd:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:videoPlayerItem];
[self setVideoPlayer:[AVPlayer playerWithPlayerItem:videoPlayerItem]];
[scenePlayerView setVideoPlayer:videoPlayer];
}
});
}];
}
When triggered, this calls my method to effectively rewind and play the clip again:
-(void)videoPlayerItemDidReachEnd:(NSNotification *)notification
{
[videoPlayerItem seekToTime:kCMTimeZero];
[videoPlayer play];
}
The problem is, there is a brief but visible pause in the video playback every time it hits this method and loops back to the beginning.
The video clips are H.264 and have been tested in other players to ensure that they have no visible "skips" in their content. This is all happening under iOS6 both in the Simulator and on an iPad2 and iPad3.
What am I doing wrong?
You have two possible approaches to get a really professional looking loop with no glitches (AVPlayer by itself will not work). First, you could take your original video and decode it to a series of RGB frames (images). Then encode a new h.264 video and feed the frames into a longer h.264 video that is much longer than the first. For example, you might encode a 10 second looping clips 6 times to make a clip that last one minute or 6 * 5 to make a clip that would play for 5 minutes without glitching when the loop restarts. Then, open the longer clip and play it with AVPlayer and it will not glitch for a period of time.
The second approach would be to use an existing library that already handles seamless looping. You can take a look at my library, see my answer to basically the same question iphone-smooth-transition-from-one-video-to-another. The character in the example at the linked answer uses a repeating "loop" of one video clip that loops over and over when no buttons have been pressed.
Unfortunately it appears this actually is not currently possible using AVPlayer as it stands- there is an unavoidable hiccup upon beginning playback in an AVPlayer in every case. So "messier" hacks appear to be the only way to solve this, using multiple AVPlayers, etc.
I managed to get it working with two AVPlayer, two AVPlayerLayer added to two different views (I've tried add to the same view and the upper one get stuck once in a while), and switch alpha value between these two views.

Resources