How can I update music volume on iPhone, through an UISlider? - iphone

I've tried to make an UISlider that controls background music volume, and whatever I set the value to should be the volume of the music. The trouble is, when I run the app in simulator, and move the slider, the volume stays that of the original volume, it doesn't update.
I am new to programming so I still need help with the basics.
Here is my viewcontroller.h:
#interface FifthViewController : UIViewController <AVAudioPlayerDelegate> {
IBOutlet UISlider *slider;
IBOutlet UIAlertView *alert;
AVAudioPlayer *theAudio;
}
-(IBAction)alertbutton;
-(IBAction)changeVolume;
#end;
and here is the viewcontroller.m:
- (void)viewDidLoad
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"background music" ofType:#"mp3"];
AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
theAudio.numberOfLoops = -1;
theAudio.volume=slider.value;
[super viewDidLoad];
}
I have connected "slider" to a horizontal slider and the sound plays and loops. And if I set the value of the slider higher or lower in Xcode, when I run the app, the volume adjusts accordingly. But if in the app I change the value of the slider, the volume remains the same . Can anyone look at my code and tell me what I'm doing wrong and how to fix it?

Assuming you have an instance of AVAudioPlayer setup in your controller.
Set the slider to run from 0.0 to 1.0 and connect it to an action.
-(void)volumeValueChange:(UISlider *)sender
{
(AVAudioPlayer *)myaudioplayer.volume = sender.value;
}

//.m implementation where audioPlayer is an an object of AVAudioPlayer
-(void)volumeValueChange:(UISlider *)sender
{
audioPlayer.volume = sender.value;
}

Related

MPMoviePlayerViewController won't play larger mp4 files

What I have are 2 links to 2 versions of the same movie, one in lower definition the other in higher, both .mp4 format.
It plays the low-def just fine, but when I click the link for the HD version the movie player pops up like it should then dismisses itself back to the original view controller. If I click it again, it works, but the first try usually fails. Like something with threading is going on and succeeding or not. From what I've read it's an issue with ARC but I can't seem to get it right.
I want to use the MPMoviePlayerViewController because I like how it by default acts as a modal popup. I tried with a MPMoviePlayerController but you have to set the view then handle rotations it seems.
I'm not getting any crashes or any warnings in the log inside Xcode either.
Here's my code:
#interface VideoInfoViewController ()
#property (nonatomic, strong) MPMoviePlayerController *player;
#end
- (IBAction)playLowVideo:(id)sender {
[self playVideoFromURL:[NSURL URLWithString:_video.video_url_low]];
}
- (IBAction)playHDVideo:(id)sender {
[self playVideoFromURL:[NSURL URLWithString:_video.video_url_HD]];
}
- (void)playVideoFromURL:(NSURL *)url {
MPMoviePlayerViewController *playerViewController = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
_player = playerViewController.moviePlayer;
_player.scalingMode = MPMovieScalingModeFill;
[_player prepareToPlay];
[self presentMoviePlayerViewControllerAnimated:playerViewController];
}
ETA:
found this tutorial: http://josebolanos.wordpress.com/2011/09/28/dismissing-mpmovieplayerviewcontroller-the-right-way/
- (void)playVideoFromURL:(NSURL *)url {
MPMoviePlayerViewController *player = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
[self presentModalViewController:player animated:YES];
[player.moviePlayer prepareToPlay];
[player.moviePlayer play];
}
still doesn't work.

How to use AVPlayer in multiple view and resume controls?

i create an app with xcode 4.6 on iOS 6.1 with a TabBar and 2 different tableView.
Each table view read a line form a file.plist and when tap on a row, you load a DetailView.
The DetailViewController is the same for the 2 TableView but:
If start app tap on a first button i see FirstView with my table and Audio List, if I choose one file on list I load a Detail view and listener my file very well, but if now tap on second view on TabBar i can start playing other audio file from the second view but i listen overlay to firs audio and AVplayer not override.
There my coding:
From TableView loading plist:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if([#"detailList" isEqualToString:segue.identifier]) {
NSIndexPath *index = [self.tableView indexPathForCell:sender];
[[segue destinationViewController] setSaved:[loadData objectAtIndex:index.row]];
}
}
In a detali view:
if (mysound.rate == 1.0) {
UIImage *img = [UIImage imageNamed:#"Play_BT.png"];
[control setImage:img forState:UIControlStateNormal];
[mysound pause];
} else {
UIImage *img = [UIImage imageNamed:#"Pause_BT.png"];
[control setImage:img forState:UIControlStateNormal];
NSURL *url = [NSURL URLWithString:[saved objectForKey:#"audio"]];
mysound = [[AVPlayer alloc] initWithURL:url];
[mysound setAllowsExternalPlayback:YES];
[mysound setUsesExternalPlaybackWhileExternalScreenIsActive: YES];
[mysound play];
}
}
Here incoming the issues, this code working very goog, but if tapo on tab bar and load other audio from other plist I listen Audio overlay.
How can use AVPlayer in Override the NSURL *url = [NSURL URLWithString:[saved objectForKey:#"audio"]];when change from tabbar?
Thanks.
Solved, using this code:
In my AppDelegate .h adding
#interface AppDelegate : UIResponder <UIApplicationDelegate> {
AVPlayer *MyPlayer;
}
#property (strong, nonatomic) AVPlayer *MyPlayer;
in my AppDelegate .m inside didFinishLaunchingWithOptions adding
[MySound superclass];
Now can calling a method in all app with this code directly inside a .m file:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSURL *url = [NSURL URLWithString:[saved objectForKey:#"link"]];
appDelegate.MySound = [[AVPlayer alloc] initWithURL:url];
[appDelegate.MySound setAllowsExternalPlayback:YES];
[appDelegate.MySound setUsesExternalPlaybackWhileExternalScreenIsActive: YES];
[appDelegate.MySound play];
With this method now is possible controlling the AVPlayer evry where in the APP!!
I Hope this Help any guys ;)

When using storyboards, and changing a view, sound will not stop playing in new view

I am trying to do something similar to what was requested in this question:
Playing audio with controls in iOS
I am using Storyboards with XCode 4.2. On my initial view page, I just have buttons that call other views, and no sounds are played there. These other views contain a UINavigationController with a BarButtonItem to allow you to go back. Other view pages will have buttons that allow one to play a sound. Each sound has its own play button, and there are resume, pause and stop buttons.
All sounds play fine, but if I hit the back button to the main page, the sound keeps playing. The desired behavior is for the sound to stop when navigating back to the main page via the back button.
Before storyboards, I could easily code a back button to stop the audio, but storyboards appear not that simple. It appears that I have to implement the method prepareForSegue. Okay, I can set the Segue identifier can be set in the Attributes Inspector, and referring back to the earlier post, I will use showPlayer.
But I was thinking I could code the prepareForSegue in one of my sound views, as seen in this cool example:
http://www.scott-sherwood.com/?p=219
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([[segue identifier] isEqualToString:#"showPlayer"]){
SoundPageController *theAudio = (SoundPageController *)[segue ViewController];
theAudio.delegate = self;
}
}
In the main page ViewController.m, I tried adding:
#property (strong, nonatomic) AVAudioPlayer *theAudio;
And I tried adding something like:
- (void)viewDidLoad {
[super viewDidLoad];
// this is the important part: if we already have something playing, stop it!
if (audioPlayer != nil)
{
[audioPlayer stop];
}
// everything else should happen as normal.
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
I wasn't able to get this to work, so I reverted the changes back to original. I will put my simplified code below, and if you have suggestions how to do it right, please let me know!
ViewController.h:
#interface ViewController : UIViewController {
}
ViewController.m (pretty much default):
#import "ViewController.h"
#import "AppDelegate.h"
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
SoundPage1.h:
#import
#import <AVFoundation/AVAudioPlayer.h>
#interface occupy : UIViewController <AVAudioPlayerDelegate> {
AVAudioPlayer* theAudio;
}
//-(IBAction)PressBack:(id)sender; now the back button is linked up through storyboard
-(IBAction)pushButton1;
-(IBAction)pushButton2;
-(IBAction)play;
-(IBAction)stop;
-(IBAction)pause;
#end
SoundPage1.m
#import "SoundPage1.h"
#import "AppDelegate.h"
#import "ViewController.h"
#implementation SoundPage1
-(IBAction)pushButton {
NSString *path = [[NSBundle mainBundle] pathForResource:#"sound1" ofType:#"mp3"];
if(theAudio)[theAudio release];
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
theAudio.volume = 1.0;
[theAudio play];
}
-(IBAction)pushButton2 {
NSString *path = [[NSBundle mainBundle] pathForResource:#"sound2" ofType:#"mp3"];
if(theAudio)[theAudio release];
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
theAudio.volume = 1.0;
[theAudio play];
}
// Old code from XCode 3.x when creating a back button that could stop the audio was easy
//-(IBAction)PressBack:(id)sender{
// [theAudio stop];
// ViewController* myappname = [[ViewController alloc] initWithNibName:#"ViewController" bundle:nil];
// [self.navigationController pushViewController:myappname animated:NO];
// }
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
Add in the code for play, stop and pause for the buttons.
I tried to format this, sorry in advance if it is hard to read.
Thanks for any suggestions!
Rob
You should stop the AVAudioPlayer in viewWillDisappear.
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if(theAudio && theAudio.isPlaying) {
[theAudio stop];
}
}
ViewDidUnload is only called by the program when the device is reaching the end of memory capacity, not when you change views. Only just found this out myself this week, while struggling with the same problem.
Hope that clears things up.

Can't play video file

I'm probably missing something really obvious.
I've included <MediaPlayer/MediaPlayer.h> and have this code:
NSURL *videoURL = [NSURL fileURLWithPath:pathToFile];
MPMoviePlayerViewController *mediaPlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:videoURL];
[self presentMoviePlayerViewControllerAnimated:mediaPlayer];
mediaPlayer.view.backgroundColor = [UIColor blackColor];
[mediaPlayer release];
But the video won't play. I copied the code from another place where the video works perfectly.
pathToFile is correct becuase the variable is used in previous lines to move the video from the resources folder to the documents directory.
Any ideas why it might not be working?
Thanks
You can use following code except to presentMoviePlayerViewControllerAnimated
NSString *movieFile=[[NSBundle mainBundle] pathForResource:#"movie" ofType:#"m4v"];
moviePlayer= [[MPMoviePlayerController alloc] initWithContentURL:url];
moviePlayer.view.frame = self.view.frame;
[self.view addSubview:moviePlayer.view];
[moviePlayer setFullscreen:YES animated:YES];
this works fine for me.
I don't think presentMoviePlayerViewControllerAnimated retains its receiver, so it looks as though you're releasing your movie player too early. You could try making mediaPlayer a retained property:
#interface MyClass : SuperClass {
MVMoviePlayerViewController *mediaPlayer;
}
#property (nonatomic, retain) MVMoviePlayerViewController *mediaPlayer;
#end
#implementation MyClass
#synthesize mediaPlayer;
// rest of class implementation here...
#end
Then initialise as so:
self.mediaPlayer = [[[MPMoviePlayerViewController alloc]
initWithContentURL:videoURL] autorelease];
And release afterwards with:
self.mediaPlayer = nil;
(To write code that happens after the video has finished playing, check out the MPMoviePlayerPlaybackDidFinishNotification notification.)
Also bear in mind that presentMoviePlayerViewControllerAnimated first appeared in iOS 3.2, so this code won't work on earlier iOS versions. But I don't think that's the problem in this case.

I put a button on a table view cell that play sound when they are pressed but

I put a button on a table view cell that play sound when they are pressed, when I press the button it stop the sound. But pressing another button on another cell it doesn't plays another sound while the other still playing. I hope that when another button is pressed in another table cell it will stop the playing sound.
Here is my code
.h file
I enter this on #interface bracket AVAudioPlayer *talkSound;
.m
NSString *myExamplePath = [[NSBundle mainBundle] pathForResource:#"kumusta" ofType:#"m4a"];
if (talkSound.playing) {
[talkSound stop];
[talkSound release];
}
talkSound =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:myExamplePath] error:NULL];
talkSound.delegate = self; /*with this here it says theres no delegate so i go an add AVAudioPlayerDelegate and i get tons of errors of connot find protocol declaration*/
[talkSound play];
I don't know if this is the problem, but you don't need to release and reallocate the AVAudioPlayer every time. Just stopping and starting it should work fine, like:
if (talkSound.playing) {
[talkSound stop];
}
[talkSound play];
Then you can just alloc/init the AVAudioPlayer once, perhaps in viewDidLoad.