Question

I'm currently making a live stream music app, and i've got all the buttons to work and play sounds from them.

However, if one sound is playing, when i press another button, rather than stopping the original sound, it just plays over it, please help me how to fix this?

Many thanks

- (IBAction)Play1:(id)sender {

    NSString *stream = @".mp3"
    ;

    NSURL *url = [NSURL URLWithString:stream];

    NSURLRequest *urlrequest = [NSURLRequest requestWithURL: url];

    [Webview1 loadRequest:urlrequest];
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

    [[AVAudioSession sharedInstance] setActive: YES error: nil];

    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

    [audioPlayer play];

    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];


}
Was it helpful?

Solution

It's up to you to implement this behaviour. I suggest you keep track of any AVAudioPlayer that might be playing and stop it before creating and starting a new one.

eg, you could use a property to store every AVAudioPlayer you create. Then, before creating a new one, stop the old one.

There's many ways to do this. Say you have a URL for each button, here's one possible procedure:

// note that audioPlayer is a property. It might be defined like this:
// @property (nonatomic,strong) AVAudioPlayer *audioPlayer

- (IBAction)button1Pressed:(id)sender {
    NSString *stream = @"url1.mp3";
    [self playUrl:[NSURL URLWithString:stream]];
}

- (IBAction)button2Pressed:(id)sender {
    NSString *stream = @"url2.mp3";
    [self playUrl:[NSURL URLWithString:stream]];
}

- (void) playUrl:(NSURL *) url {
    //stop a previously running audioPlayer if it is running:
    [audioPlayer pause]; //this will do nothing if audioPlayer is nil
    //create a new one and start it:
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    [audioPlayer start];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top