My buttons play all the same sound? - ios

Here is my MainViewController.m
#import "MainViewController.h"
#interface MainViewController ()
#end
#implementation MainViewController
#synthesize audioPlayer;
#synthesize soundsArray;
-(void)prepareSounds
{
NSString *filepath= [[NSBundle mainBundle] pathForResource:#"Sounds" ofType:#"plist"];
self.soundsArray = [[NSArray alloc] initWithContentsOfFile:filepath];
}
- (IBAction)playSound:(id)sender {
UIButton *buttonPressed = (UIButton *)sender;
NSString *soundName = [soundsArray objectAtIndex:(buttonPressed.tag -1)];
NSString *path = [[NSBundle mainBundle] pathForResource:soundName ofType:#"mp3"];
NSURL *file = [[NSURL alloc] initFileURLWithPath:path];
AVAudioPlayer *p = [[AVAudioPlayer alloc]
initWithContentsOfURL:file error:nil];
self.audioPlayer = p;
[self.audioPlayer play];
}
- (IBAction)playSound2:(id)sender {
UIButton *buttonPressed = (UIButton *)sender;
NSString *soundName = [soundsArray objectAtIndex:(buttonPressed.tag -2)];
NSString *path = [[NSBundle mainBundle] pathForResource:soundName ofType:#"mp3"];
NSURL *file = [[NSURL alloc] initFileURLWithPath:path];
AVAudioPlayer *p = [[AVAudioPlayer alloc]
initWithContentsOfURL:file error:nil];
self.audioPlayer = p;
[self.audioPlayer play];
}
- (IBAction)playSound3:(id)sender {
UIButton *buttonPressed = (UIButton *)sender;
NSString *soundName = [soundsArray objectAtIndex:(buttonPressed.tag -3)];
NSString *path = [[NSBundle mainBundle] pathForResource:soundName ofType:#"mp3"];
NSURL *file = [[NSURL alloc] initFileURLWithPath:path];
AVAudioPlayer *p = [[AVAudioPlayer alloc]
initWithContentsOfURL:file error:nil];
self.audioPlayer = p;
[self.audioPlayer play];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Flipside View
- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)showInfo:(id)sender
{
FlipsideViewController *controller = [[FlipsideViewController alloc] initWithNibName:#"FlipsideViewController" bundle:nil];
controller.delegate = self;
controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:controller animated:YES completion:nil];
}
#end
My MainViewController.h
#import <UIKit/UIKit.h>
#import "FlipsideViewController.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#interface MainViewController : UIViewController <FlipsideViewControllerDelegate> {
AVAudioPlayer *audioPlayer;
NSArray *soundsArray;
}
#property(nonatomic, retain) AVAudioPlayer *audioPlayer;
#property(nonatomic, retain) NSArray *soundsArray;
-(void)prepareSounds;
- (IBAction)playSound:(id)sender;
- (IBAction)playSound2:(id)sender;
- (IBAction)playSound3:(id)sender;
#end
In the 'Supporting Files' folder I have an array of strings with the name of the sound files I want to play, and in the 'Supporting Files' folder I have a folder named 'Sounds', which contains the sound files.
All of my buttons play the same sound. Can someone please provide some insight. Thanks!

I think the problem may be in this line playSound:
NSString *soundName = [soundsArray objectAtIndex:(buttonPressed.tag -1)]
which is repeated in playSound2 and playSound3 with "buttonPressed.tag -2" and "buttonPressed.tag -3".
If your buttonPressed.tags are set to 1, 2, and 3, then each time "buttonPressed.tag -X" is likely evaluating to 0, and playing the sound of the first file in the array.

You are repeating the code to do the same task.
Add all your buttons IBAction to a single method (say it as playSound)
Implement the method like:
- (IBAction)playSound:(UIButton *)sender
{
NSString *soundName = [soundsArray objectAtIndex:(sender.tag -1)];
NSString *path = [[NSBundle mainBundle] pathForResource:soundName ofType:#"mp3"];
NSURL *file = [[NSURL alloc] initFileURLWithPath:path];
AVAudioPlayer *p = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:nil];
self.audioPlayer = p;
[self.audioPlayer play];
}
There is no need of writing same code for each individual button.

SOLVED: prepareSounds() was never called. Here is the working code:
#import "MainViewController.h"
#interface MainViewController ()
#end
#implementation MainViewController
#synthesize audioPlayer;
#synthesize soundsArray;
-(void)prepareSounds
{
NSString *filepath= [[NSBundle mainBundle] pathForResource:#"Sound" ofType:#"plist"];
self.soundsArray = [[NSArray alloc] initWithContentsOfFile:filepath];
}
- (void)stopAudio
{
if (audioPlayer!= nil) {
[audioPlayer stop];
//do some task for changing the Image i.e setting the default image
}
}
- (IBAction)playSound:(UIButton *)sender
{
UIButton *btn = (UIButton*)sender;
NSString *soundName = [soundsArray objectAtIndex:(btn.tag - 1)];
NSString *path = [[NSBundle mainBundle] pathForResource:soundName ofType:#"mp3"];
NSURL *file = [[NSURL alloc] initFileURLWithPath:path];
AVAudioPlayer *p = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:nil];
self.audioPlayer = p;
if([audioPlayer isPlaying])
{
[self stopAudio];
}
[self.audioPlayer play];
}
- (void)viewDidLoad
{
[self prepareSounds];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Flipside View
- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)showInfo:(id)sender
{
FlipsideViewController *controller = [[FlipsideViewController alloc] initWithNibName:#"FlipsideViewController" bundle:nil];
controller.delegate = self;
controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:controller animated:YES completion:nil];
}
#end

Related

How to play the music continously which are stored in NSArray?

In tableview footer i have a play button to play the music, as the music starts tableview scrolls automatically according to the audio played but if the user tap on particular cell, the content in the particular cell is playing and stops but i want to continue the music from where the use taps to the end. Below is the code. Please help.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int ref =(int) indexPath.row;
NSString *filePath = [soundArray objectAtIndex:ref];
NSString *Path = [[NSBundle mainBundle] pathForResource:filePath ofType:#"mp3"];
NSURL *musicFile = [NSURL fileURLWithPath:Path];
myAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
if (playing == YES) {
[playButton setBackgroundImage:[UIImage imageNamed:#"pause_White.png"] forState:UIControlStateNormal];
[myAudioPlayer play];
// playing = NO;
}
if (playing == NO) {
// [playButton setBackgroundImage:[UIImage imageNamed:#"play_white.png"] forState:UIControlStateNormal];
}
}
SoundArray contains trimmed music. How to continue the song ? Help much appreciated.
Here is my code as per my concept. You may have to manage it more as its just a sample
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
isMainMusic = NO;
// Construct URL to sound file
NSString *path = [NSString stringWithFormat:#"%#/1.mp3", [[NSBundle mainBundle] resourcePath]];
mainMusicUrl = [NSURL fileURLWithPath:path];
NSString *path1 = [NSString stringWithFormat:#"%#/2.mp3", [[NSBundle mainBundle] resourcePath]];
secondMusicUrl = [NSURL fileURLWithPath:path1];
}
-(void)playSecondaryMusic
{
if ([playMainMusic isPlaying]) {
[playMainMusic pause];
}
if (playSecondaryMusic) {
playSecondaryMusic.delegate = nil;
playSecondaryMusic = nil;
}
isMainMusic = NO;
playSecondaryMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:secondMusicUrl error:nil];
playSecondaryMusic.delegate = self;
[playSecondaryMusic play];
}
- (IBAction)playMainMusic:(UIButton *)sender {
if (playMainMusic) {
playMainMusic.delegate = nil;
playMainMusic = nil;
}
isMainMusic = YES;
playMainMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:mainMusicUrl error:nil];
playMainMusic.delegate = self;
[playMainMusic play];
}
//Delegate method
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
if (isMainMusic)
{
NSLog(#"Main music");
}
else
{
NSLog(#"Second music");
[playMainMusic play];
isMainMusic = YES;
}
}

Stopping sounds and looping them in xcode

Ok so im pretty new to Xcode and am trying to make a simple app. i need my sound to keep looping and stop when i press the stop button. Please help and thanks in advance. here is my code so far.
as you can see the sound plays once then stops .
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize Images;
-(IBAction)start:(id)sender;{
AudioServicesPlaySystemSound(PlaySoundID);
Images.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:#"Light.png"],
[UIImage imageNamed:#"Light1.png"],
[UIImage imageNamed:#"Light2.png"],
[UIImage imageNamed:#"Light3.png"], nil];
Images.animationRepeatCount = 99999999;
Images.animationDuration = .2;
[Images startAnimating];
[self.view addSubview:Images];
}
-(IBAction)stop:(id)sender;{
[Images stopAnimating];
}
- (void)viewDidLoad
{
NSURL *SoundURL = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:#"Siren" ofType:#"wav"]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)SoundURL, &PlaySoundID);
[super viewDidLoad];
Images.image = [UIImage imageNamed:#"Light.png"];
[self.view addSubview:Images];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
NSURL *soundURL = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:#"Siren"
ofType:#"wav"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL
error:nil];
for "infinite" number of loops:
audioPlayer.numberOfLoops = -1;

how to import songs dynamically to our app in Objective C

I tried iPhone app.In this app I need to import all songs into table-view when I click on import button.I don't know how to import songs dynamically.Please tell me what are the Frameworks to be used.
But i have played Locally saved songs like code:-
using this two Frameworks `AVFoundation.framework,MediaPlayer.framework
#import "ViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#interface ViewController ()
#property (nonatomic, strong) AVAudioPlayer *audioPlayer;
- (IBAction)playSound:(id)sender;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [mainBundle pathForResource:#"drum" ofType:#"mp3"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSError *error = nil;
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData
error:&error];
[self.audioPlayer prepareToPlay];
self.audioPlayer.numberOfLoops = -1;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)playSound:(id)sender {
[self.audioPlayer play];
UIView *wrapperView = [[UIView alloc] initWithFrame:CGRectMake(20, 120, 260, 20)];
wrapperView.backgroundColor = [UIColor clearColor];
[self.view addSubview:wrapperView];
MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame: wrapperView.bounds];
[wrapperView addSubview:volumeView];
}
#end
Output for this code is songs played locally but I need when I click play button it should import 10 songs in tableView and then songs mush be played.
Please give me any idea.
Thanks in advanced.

Thread 1:breakpoint 5.1: incompatible pointer types sending 'MWPhotoBrowser *' to parameter of type UIView

I am trying to create a photo gallery with storyboards using MWPhotoBrowser. I have added a blue view to the first view but receive the error message
Thread 1:breakpoint 5.1:incompatible pointer types sending 'MWPhotoBrowser *' to parameter of type UIView.
Code:
In .h file:
#import <Foundation/Foundation.h>
#import "RESideMenu.h"
#import "MWPhotoBrowser.h"
#interface DEMOSevenViewController : UIViewController<MWPhotoBrowserDelegate>
#property (nonatomic, strong) NSMutableArray *photos;
#property (nonatomic, strong) NSMutableArray *thumbs;
#property (strong, nonatomic) UIView *container;
- (IBAction)showMenu;
#end
In .m file:
#import "DEMOSevenViewController.h"
#interface DEMOSevenViewController ()
#end
#implementation DEMOSevenViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *photos = [[NSMutableArray alloc] init];
NSMutableArray *thumbs = [[NSMutableArray alloc] init];
MWPhoto *photo;
BOOL displayActionButton = YES;
BOOL displaySelectionButtons = NO;
BOOL displayNavArrows = NO;
BOOL enableGrid = YES;
BOOL startOnGrid = NO;
photo = [MWPhoto photoWithImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"photo5" ofType:#"jpg"]]];
photo.caption = #"White Tower";
[photos addObject:photo];
photo = [MWPhoto photoWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"photo2" ofType:#"jpg"]]];
photo.caption = #"The London Eye is a giant Ferris wheel situated on the banks of the River Thames, in London, England.";
[photos addObject:photo];
photo = [MWPhoto photoWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"photo3" ofType:#"jpg"]]];
photo.caption = #"York Floods";
[photos addObject:photo];
photo = [MWPhoto photoWithImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"photo4" ofType:#"jpg"]]];
photo.caption = #"Campervan";
[photos addObject:photo];
// Thumbs
photo = [MWPhoto photoWithImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"photo5t" ofType:#"jpg"]]];
[thumbs addObject:photo];
photo = [MWPhoto photoWithImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"photo2t" ofType:#"jpg"]]];
[thumbs addObject:photo];
photo = [MWPhoto photoWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"photo3t" ofType:#"jpg"]]];
[thumbs addObject:photo];
photo = [MWPhoto photoWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"photo4t" ofType:#"jpg"]]];
[thumbs addObject:photo];
// Options
startOnGrid = YES;
self.photos = photos;
self.thumbs = thumbs;
// Create browser
MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
browser.displayActionButton = displayActionButton;
browser.displayNavArrows = displayNavArrows;
browser.displaySelectionButtons = displaySelectionButtons;
browser.alwaysShowControls = displaySelectionButtons;
browser.wantsFullScreenLayout = YES;
browser.zoomPhotosToFill = YES;
browser.enableGrid = enableGrid;
browser.startOnGrid = startOnGrid;
[browser setCurrentPhotoIndex:0];
UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browser];
nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:nc animated:YES];
[_container addSubview:browser];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
return _photos.count;
}
- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
if (index < _photos.count)
return [_photos objectAtIndex:index];
return nil;
}
- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser thumbPhotoAtIndex: (NSUInteger)index {
if (index < _thumbs.count)
return [_thumbs objectAtIndex:index];
return nil;
}
- (IBAction)showMenu
{
[self.sideMenuViewController presentMenuViewController];
}
#end
The problem is here, you are adding a ViewController and not a view where a View is expected.
[_container addSubview:browser];
Try:
[_container addSubview:browser.view];
Also, not entirely sure why you add it to a NavigationController and to _container depending on the rest of your code that might also cause problems, but the previous thing is what causes your error.

iOS : How to autostop the sound file on the PickerViewController when user select a new picker?

I have one music player with multiple sounds. My question is when i pick one of the object in the picker view, it will play automatically, but when i select a new one, the old sound won't stop. The sound will overlap with the new one. How do I autostop it? Here is my code for troubleshoot :
H File :
#import <UIKit/UIKit.h>
#import <AVFoundation/AVAudioPlayer.h>
#interface musixGreetingViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource, AVAudioPlayerDelegate>{
UIPickerView *picker;
UILabel *musicTitle;
NSMutableArray *musicList;
AVAudioPlayer *audioPlayer;
}
#property (nonatomic, retain) IBOutlet UIPickerView *picker;
#property (nonatomic, retain) IBOutlet UILabel *musicTitle;
#property (nonatomic, retain) NSMutableArray *musicList;
-(IBAction)playSelectedMusic:(id)sender;
#end
M File :
- (void)viewDidLoad
{
[super viewDidLoad];
musicList = [[NSMutableArray alloc] initWithObjects:#"m1",#"m2",#"m3",#"m6",#"m4", #"m5",nil];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
//[self playSelectedMusic:self];
if ([[musicList objectAtIndex:row] isEqual:#"m1"])
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"m1" ofType:#"mp3"];
AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
pickerView.delegate = self;
[theAudio play];
NSString *resultString = [[NSString alloc] initWithFormat:
#"m1",
[musicList objectAtIndex:row]];
musicTitle.text = resultString;
}
if ([[musicList objectAtIndex:row] isEqual:#"m2"])
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"m2" ofType:#"mp3"];
AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
pickerView.delegate = self;
[theAudio play];
NSString *resultString = [[NSString alloc] initWithFormat:
#"m2",
[musicList objectAtIndex:row]];
musicTitle.text = resultString;
}
-(IBAction)playSelectedMusic:(id)sender{
I want the music play here, how to do so without autoplay the music in the picker view?
}
This will reset the player to the beginning:
[theAudio setCurrentTime:0.0];

Resources